iOS使用定时器导致内存泄漏解决方案

1. 使用block
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf timerTest];
    }];

2. 利用Runtime的消息转发机制
//.h
@interface YZTimerProxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end

//.m
@implementation YZTimerProxy

+ (instancetype)proxyWithTarget:(id)target {
    // NSProxy对象不需要调用init,因为它本来就没有init方法
    YZTimerProxy *proxy = [YZTimerProxy alloc];
    proxy.target = target;
    return proxy;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    return [self.target methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    [invocation invokeWithTarget:self.target];
}
@end
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[YZTimerProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • # 欢迎使用 Cmd Markdown 编辑阅读器 ------ 我们理解您需要更便捷更高效的工具记录思想,整理笔...
    raidery阅读 1,085评论 0 1
  • 罗大佑的《恋曲1990》 乌溜溜的黑眼珠和你的笑脸 怎么也难忘记你容颜的转变 轻飘飘的旧时光就这么溜走 转头回去看...
    如意ylm阅读 249评论 3 4
  • 这次行走的起因是朋友在群里发了个广告,朋友的朋友要组织有兴趣的人去北京平谷国际徒步大道。当时刚刚从江苏回来,玩心未...
    微微向晚阅读 250评论 0 1
  • 绝望的内心想哭找不到眼泪是憋屈 是恨 是不解 是害怕 是无助是死都结束不了的痛这上帝的恩赐啊叫我如何供奉我的虔诚冷...
    夜语阅读 412评论 0 1