『ios』来自NSTimer的坑|『ios』来自NSTimer的坑 ,告别循环, 最全的方法总结

因为一个NStimer的循环引用没有释放问题,导致一次性会走两遍的回调
问题所在

self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(doTimeEvent) userInfo:nil repeats:YES];

置于循环引用的原因,vc强引用timer,timer又强引用他的target,而target又是self,self也就是vc了。这就形成了一个环。

『ios』来自NSTimer的坑|『ios』来自NSTimer的坑 ,告别循环, 最全的方法总结
文章图片
image.png 解决 如何解决呢?无非就是打破这个环。
首先苹果的api已经解决了这个问题,但是只支持10.0的api。
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

下面就来看看,各路大神是如何解决的这个问题。 首先是YYKIt的解决办法,一直在用,各种block,用的不亦乐乎
@interface NSTimer (YYAdd) + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats; + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats; @end

YYSYNTH_DUMMY_CLASS(NSTimer_YYAdd) @implementation NSTimer (YYAdd)+ (void)_yy_ExecBlock:(NSTimer *)timer { if ([timer userInfo]) { void (^block)(NSTimer *timer) = (void (^)(NSTimer *timer))[timer userInfo]; block(timer); } } + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats { return [NSTimer scheduledTimerWithTimeInterval:seconds target:self selector:@selector(_yy_ExecBlock:) userInfo:[block copy] repeats:repeats]; } + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats { return [NSTimer timerWithTimeInterval:seconds target:self selector:@selector(_yy_ExecBlock:) userInfo:[block copy] repeats:repeats]; } @end

从代码中我们可以很清楚的看到,yykit是把nstimer自身作为target,来调用自己的方法,
然后通过userinfo把block传过去,从而实现以一种相当优雅的形式来解决weaktimer的问题。
下面说的这两种方法都是从同一个人的博客中看到的。 其实也是提供了另外两种思路。
利用RunTime解决由NSTimer导致的内存泄漏
利用NSProxy解决NSTimer内存泄漏问题
首先是利用runtime解决
来看具体代码实现
@interface TableViewController () @property (nonatomic,strong) id timerTarget; @end static const void * TimerKey = @"TimerKey"; static const void * weakKey = @"weakKey"; @implementation TableViewController - (void)viewDidLoad { [super viewDidLoad]; _timerTarget = [NSObject new]; //初始化timerTarge对象class_addMethod([_timerTarget class], @selector(timerEvent), (IMP)timMethod, "v@:"); //动态创建timerEvent方法NSTimer *_timer; _timer = [NSTimer timerWithTimeInterval:1 target:_timerTarget selector:@selector(timerEvent) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes]; //创建计时器target对象为_timerTargetobjc_setAssociatedObject(_timerTarget, TimerKey, _timer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(_timerTarget, weakKey, self, OBJC_ASSOCIATION_ASSIGN); //将self对象与NSTimer对象与_timerTarget对象关联 } void timMethod(id self,SEL _cmd) { TableViewController *tabview = objc_getAssociatedObject(self, weakKey); [tabview performSelector:_cmd]; } -(void)timerEvent { NSLog(@"%@",NSStringFromClass([self class])); } -(void)dealloc { NSTimer *timer = objc_getAssociatedObject(_timerTarget, TimerKey); [timer invalidate]; NSLog(@"%@--dealloc",NSStringFromClass([self class])); }

首先添加了timMethod 的IMP 然后利用runtime为timeTarget类添加方法。
timeTarget就是nstimer的target。
OBJC_ASSOCIATION_RETAIN_NONATOMIC和OBJC_ASSOCIATION_ASSIGN分别代表强引用和弱引用。也就是说self. timerTarget是弱引用的。这样就不会引起释放不了的问题。
第二种是NSProxy来解决的,结合消息转发来解决的。
好早就知道NSProxy是根类,NSProxy与NSObject一样是根类,都遵守协议。
NSProxy与NSObject的子类都能实现,不过NSProxy从类名来看是代理类专门负责代理对象转发消息的。相比NSObject类来说NSProxy更轻量级,通过NSProxy可以帮助Objective-C间接的实现多重继承的功能。
说到消息转发无非就是那三个步骤。
+(BOOL)resolveClassMethod:(SEL)sel; -(BOOL)respondsToSelector:(SEL)aSelector;

-(id)forwardingTargetForSelector:(SEL)aSelector;

-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector; - (void)forwardInvocation:(NSInvocation *)invocation;

来看下作者是怎么实现的。
.h文件#import @interface LSYViewController : UIViewController @end @interface LSYProxy : NSProxy @property (nonatomic,weak) id obj; @end .m文件#import "LSYViewController.h" @interface LSYViewController () @property (nonatomic,strong) LSYProxy *proxy; @property (nonatomic,strong) NSTimer *timer; @property (nonatomic) NSInteger count; @end @implementation LSYViewController -(void)viewDidLoad { [super viewDidLoad]; self.proxy = [LSYProxy alloc]; self.proxy.obj = self; _timer = [NSTimer timerWithTimeInterval:1 target:self.proxy selector:@selector(timerEvent) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes]; } -(void)timerEvent { NSLog(@"count---%d",(int)++_count); } -(void)dealloc { NSLog(@"---dealloc----"); [_timer invalidate]; } @end #pragma mark - LSYProxy Implementation @implementation LSYProxy - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { NSMethodSignature *sig; sig = [self.obj methodSignatureForSelector:aSelector]; return sig; } - (void)forwardInvocation:(NSInvocation *)invocation { [invocation invokeWithTarget:self.obj]; } @end

利用消息转发的第三步,来给方法重新签名,重新设置target。利用消息转发来断开NSTimer对象与视图之间的引用关系。其实看了上面的代码,应该都能明白作者是怎么个想法。
剩下的这种也是某位大神所写的插件 MSWeakTimer,也是相当牛逼,是根据GCD来搞的。 【『ios』来自NSTimer的坑|『ios』来自NSTimer的坑 ,告别循环, 最全的方法总结】为什么要拿GCD来搞呢?因为NSTimer的启动和失效必须都是在同一个线程调用,否则可能没用。所以就要用GCD自带的计时器
@interface MSWeakTimer () { struct { uint32_t timerIsInvalidated; } _timerFlags; }@property (nonatomic, assign) NSTimeInterval timeInterval; @property (nonatomic, weak) id target; @property (nonatomic, assign) SEL selector; @property (nonatomic, strong) id userInfo; @property (nonatomic, assign) BOOL repeats; @property (nonatomic, ms_gcd_property_qualifier) dispatch_queue_t privateSerialQueue; @property (nonatomic, ms_gcd_property_qualifier) dispatch_source_t timer; @end + (instancetype)scheduledTimerWithTimeInterval:(NSTimeInterval)timeInterval target:(id)target selector:(SEL)selector userInfo:(id)userInfo repeats:(BOOL)repeats dispatchQueue:(dispatch_queue_t)dispatchQueue { MSWeakTimer *timer = [[self alloc] initWithTimeInterval:timeInterval target:target selector:selector userInfo:userInfo repeats:repeats dispatchQueue:dispatchQueue]; [timer schedule]; return timer; } - (id)initWithTimeInterval:(NSTimeInterval)timeInterval target:(id)target selector:(SEL)selector userInfo:(id)userInfo repeats:(BOOL)repeats dispatchQueue:(dispatch_queue_t)dispatchQueue { NSParameterAssert(target); NSParameterAssert(selector); NSParameterAssert(dispatchQueue); if ((self = [super init])) { //把nstimer所需要的所有参数都拿出来,除了userinfo都是弱引用修饰 self.timeInterval = timeInterval; self.target = target; self.selector = selector; self.userInfo = userInfo; self.repeats = repeats; NSString *privateQueueName = [NSString stringWithFormat:@"com.mindsnacks.msweaktimer.%p", self]; self.privateSerialQueue = dispatch_queue_create([privateQueueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL); //新建一个串行队列 dispatch_set_target_queue(self.privateSerialQueue, dispatchQueue); //保证目标队列再串行队列里执行self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.privateSerialQueue); //GCD里面的时间计时器 }return self; }

#pragma mark -- (void)setTolerance:(NSTimeInterval)tolerance //这里是等待时间的意思 { @synchronized(self)//加锁保证安全 { if (tolerance != _tolerance) { _tolerance = tolerance; [self resetTimerProperties]; } } } //通过查阅资料,对于tolerance有这样一个解释 由于系统底层的调度优化关系,当我们使用定时器调用fired的时候并不能立马就能运行的。可能马上运行,也可能需要等一段时间(如果当前CPU忙着做别的事情)。当时我们可以设置一个最大等待时间。 对于刚创建的timer第一次在start时间点fire,那么这个fire的时间上限为'leeway',即第一次fire不会晚于'start' + 'leeway' 。 对于重复了N次的fire,那么这个时间上限就是 MIN('leeway','interval'/2)。 如果我们使用了参数DISPATCH_TIMER_STRICT,那么系统将尽最大可能去"尽早 "启动定时器,即使DISPATCH_TIMER_STRICT比当前的发射延迟下限还低。注意就算这样,还是会有微量的延迟。MSWeakTimer中对于这个参数就是重新包装一下,名字叫tolerance,更好理解一点。 - (NSTimeInterval)tolerance { @synchronized(self) { return _tolerance; } }- (void)resetTimerProperties { int64_t intervalInNanoseconds = (int64_t)(self.timeInterval * NSEC_PER_SEC); int64_t toleranceInNanoseconds = (int64_t)(self.tolerance * NSEC_PER_SEC); dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, intervalInNanoseconds), (uint64_t)intervalInNanoseconds, toleranceInNanoseconds//最大等待时间 ); }- (void)schedule { [self resetTimerProperties]; __weak MSWeakTimer *weakSelf = self; dispatch_source_set_event_handler(self.timer, ^{//执行倒计时 [weakSelf timerFired]; }); dispatch_resume(self.timer); }- (void)fire { [self timerFired]; }- (void)invalidate { // We check with an atomic operation if it has already been invalidated. Ideally we would synchronize this on the private queue, // but since we can't know the context from which this method will be called, dispatch_sync might cause a deadlock. //在这里采用异步方法去取消计时器的原因是防止死锁 if (!OSAtomicTestAndSetBarrier(7, &_timerFlags.timerIsInvalidated))//这一块是我只知道是原子性相关的东西,应该是准确度更高,也看起来更高大上一点。 { dispatch_source_t timer = self.timer; dispatch_async(self.privateSerialQueue, ^{ dispatch_source_cancel(timer); ms_release_gcd_object(timer); }); } }- (void)timerFired { // Checking attomatically if the timer has already been invalidated. if (OSAtomicAnd32OrigBarrier(1, &_timerFlags.timerIsInvalidated)) { return; } // We're not worried about this warning because the selector we're calling doesn't return a +1 object. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [self.target performSelector:self.selector withObject:self]; #pragma clang diagnostic popif (!self.repeats) { [self invalidate]; } }

    推荐阅读