iOS开发中,涉及到定时的问题,我们通常使用NSTimer来解决,例如下面的代码。

SFClass.h

#import <Foundation/Foundation.h>

@interface SFClass : NSObject

- (void)startPolling;
- (void)stopPolling;

@end

SFClass.m

#import "SFClass.h"

@implementation SFClass {
    NSTimer *_pollTimer;
}

- (void)dealloc {
    [_pollTimer invalidate];
}

- (void)stopPolling {
    [_pollTimer invalidate];
    _pollTimer = nil;
}

- (void)doSomething {

}

- (void)startPolling {
    _pollTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
}

@end

由于定时器会保留target对象,所以上面的代码会造成SFClass对象和NSTimer对象的相互引用,会导致内存泄漏问题。

我们可以通过下面的方式来解决。

NSTimer+SFBlocksSupport.h

#import <Foundation/Foundation.h>

@interface NSTimer (SFBlocksSupport)

+ (NSTimer *)sf_scheduleTimerWithTimeInterval:(NSTimeInterval)interval block:(void (^)(void))block repeats:(BOOL)repeats;

@end

NSTimer+SFBlocksSupport.m

#import "NSTimer+SFBlocksSupport.h"

@implementation NSTimer (SFBlocksSupport)

+ (NSTimer *)sf_scheduleTimerWithTimeInterval:(NSTimeInterval)interval block:(void (^)(void))block repeats:(BOOL)repeats {
    return [self scheduledTimerWithTimeInterval:interval target:self selector:@selector(sf_blockInvoke:) userInfo:[block copy] repeats:repeats];
}

+ (void)sf_blockInvoke:(NSTimer *)timer {
    void (^block)(void) = timer.userInfo;
    if (block) {
        block();
    }
}

@end

然后,我们使用定时器的代码就要修改为下面的样子

- (void)startPolling {
    _pollTimer = [NSTimer sf_scheduleTimerWithTimeInterval:1.0 block:^{
        [self doSomething];
    } repeats:YES];
}

仔细看看代码,发现依然有保留环,再修改一下:

- (void)startPolling {
    __weak typeof(self) weakSelf = self;
    _pollTimer = [NSTimer sf_scheduleTimerWithTimeInterval:1.0 block:^{
        SFClass *strongSelf = weakSelf;
        [strongSelf doSomething];
    } repeats:YES];
}

最终解决了相互引用的问题。

最新文章

  1. 深入浅出node(2) 模块机制
  2. 【USACO 1.3】Wormholes
  3. hdu 5183. Negative and Positive (哈希表)
  4. 用AsyncTask 来实现下载图片在android开发中
  5. Select模型及tcp select模型
  6. (转) Android的Window类
  7. 16、SQL Server 复制及常见错误处理
  8. angular学习地址
  9. Qt5.4静态编译方法
  10. rownum使用方法
  11. 聚类系数(clustering coefficient)计算
  12. js读取txt文件
  13. 【做题】NOWCODER142A Ternary String——数列&amp;欧拉定理
  14. DevExpress v18.1新版亮点——Reporting篇(三)
  15. 计时器---JS
  16. CF&amp;&amp;CC百套计划2 CodeChef December Challenge 2017 Chef and Hamming Distance of arrays
  17. 用 Python 编写的 Python 解释器
  18. ArchLinux基本系统到XFCE4桌面搭建
  19. gihub简单学习 步步操作(简单易学)
  20. C++学习之路(四):线程安全的单例模式

热门文章

  1. Oracle数据库中直方图对执行计划的影响
  2. win8下安装VC6出现兼容性问题的解决办法
  3. 团队作业4——第一次项目冲刺(Alpha版本)日志集合处
  4. 201521123049 《JAVA程序设计》 第6周学习总结
  5. 201521123068《Java程序设计》第3周学习总结
  6. 201521123036 《Java程序设计》第13周学习总结
  7. 关于搭建php电商环境时缺少fileinfo、数据库安装出错问题解决办法
  8. MongoDB中的映射,限制记录和记录拼排序 文档的插入查询更新删除操作
  9. JavaScript中的alert、confirm、prompt
  10. LCA问题第二弹