循環(huán)引用問(wèn)題:
將一個(gè)NSTimer對(duì)象作為一個(gè)控制器的的屬性,這時(shí)當(dāng)前VC對(duì)NSTimer對(duì)象進(jìn)行了一次強(qiáng)引用迷守。在創(chuàng)建NSTimer對(duì)象的時(shí)候,NSTimer對(duì)象又將當(dāng)前VC作為自己的target旺入,這時(shí)NSTimer對(duì)象對(duì)當(dāng)前VC進(jìn)行了一次強(qiáng)引用兑凿,這樣就造成了NSTimer和當(dāng)前VC的循環(huán)引用,從而讓VC和NSTimer都無(wú)法釋放茵瘾,最終導(dǎo)致內(nèi)存泄漏礼华。
通常代碼:
我們可以為NSTimer創(chuàng)建一個(gè)分類,在分類中添加一個(gè)創(chuàng)建NSTimer對(duì)象的方法拗秘,以避免循環(huán)引用的問(wèn)題卓嫂。
NSTimer分類代碼:
.m中的代碼
可復(fù)制代碼:
+ (NSTimer *)resolve_scheduledTimerWithTimeInterval:(NSTimeInterval)inerval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block{
? ? return [NSTimer scheduledTimerWithTimeInterval:inerval target:self selector:@selector(resolve_blcokInvoke:) userInfo:[block copy] repeats:repeats];
}
+ (void)resolve_blcokInvoke:(NSTimer *)timer {
? ? void (^block)(NSTimer *timer) = timer.userInfo;
? ? if (block) {
? ? ? ? block(timer);
? ? }
}
使用代碼:
可復(fù)制代碼:
weakifySelf
? ? self.timer = [NSTimer resolve_scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer *timer) {
? ? ? ? strongifySelf
? ? ? ? [self doThings];
? ? ? ? NSLog(@"----------------");
? ? }];
關(guān)于weakSelf和strongSelf:
#define weakifySelf? \
__weak __typeof(&*self)weakSelf = self;
#define strongifySelf \
__strong __typeof(&*weakSelf)self = weakSelf;
demo地址:https://gitee.com/liangsenliangsen/nstimer_loop_reference.git
2019.2.1新增:
iOS10之后新增的方法里有兩個(gè)創(chuàng)建NSTimer對(duì)象的方法可以解決NSTimer不釋放的問(wèn)題。
看看幾個(gè)方法的區(qū)別:
注意:利用scheduledTimerWithTimeInterval:方法創(chuàng)建的NSTimer對(duì)象不需要手動(dòng)添加到NSRunLoop中就能使用聘殖,而利用timerWithTimeInterval:方法創(chuàng)建的NSTimer對(duì)象需要手動(dòng)添加到NSRunLoop中才能使用。 ? ? ? ?
本篇文章到這里就結(jié)束了行瑞,愿大家加班不多工資多奸腺,男同胞都有女朋友,女同胞都有男朋友血久。??