NSTimer内存泄漏问题

2019-01-19  本文已影响16人  YannChee

最近自己造了一个轮播的轮子,用到了NSTimer

在iOS10之前一般喜欢使用最常使用是的这个构造方法,这个方法会自动把timer添加到runloop中

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

官方文档的大概意思就是:
1. timer是要和runloop共同协作的
2.runloop对对应的timer保持强引用,所以当timer被添加到runloop后,自定义的代码不要对timer强引用

在iOS10后可以使用block调用的方式

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

使用block方式和使用target selector 方式调用还有一个重要的区别:target selector 方式 会对target进行强引用,而 block方式不会

总结下来就是:

1.NSTimer作为属性时,使用weak修饰:@property (nonatomic, weak) NSTimer *timer;
2.NSTimer要对target进行弱引用:注意使用 __weak __typeof(self)weakSelf = self;并不能打破此处的循环引用,一般是引入一个第三方的对象充当target来打破.常见的是 NSProxy.(NSObject类来说NSProxy更轻量级;性能更好一些)

由于本项目使用了YYKit,我直接使用了YYWeakProxy ,它继承自NSProxy,并对齐作了封装

[YYWeakProxy proxyWithTarget:self]
上一篇下一篇

猜你喜欢

热点阅读