ios10以后苹果解决了NSTimer的循环引用,调用如下方法即可:
__weak typeof (self) weakself = self;
_timer = [NSTimer scheduledTimerWithTimeInterval:0.2 repeats:YES block:^(NSTimer * _Nonnull timer) {
[weakself timeAction];
}];
用类别来实现一下它的实现:
#import "NSTimer+LiTimer.h"
@implementation NSTimer (LiTimer)
+(NSTimer *)li_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
repeats:(BOOL)repeats
block:(void(^)(NSTimer *timer))block
{
return [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(blockInvoke:) userInfo:[block copy] repeats:repeats];
}
+(void)blockInvoke:(NSTimer *)timer
{
void(^block)(NSTimer *timer) = timer.userInfo;
if (block) {
block(timer);
}
}
@end
解决NSTimer的原理,就是将它的target转移,持有timer的vc不被timer强引用。