解決定時器循環(huán)引用的問題

關于NSTimer和CADisplayLink定時器循環(huán)引用;
我這里有控制器ViewControll1和ViewControll2兩個控制器, ViewControll1 push出來ViewControll2,然后在ViewControll2寫下這些代碼,對button,NSTimer,和CADisplayLink進行驗證,其中TestBtn繼承自UIButton,重寫dealloc方法,觀察能否銷毀

@interface ViewController2 ()

@property(nonatomic,strong)TestBtn *btn;

@property(nonatomic,strong)NSTimer *timer;

@property(nonatomic,strong)CADisplayLink *displayLink;

@end

@implementation ViewController2

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor greenColor];
    
    self.btn = [[TestBtn alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
    self.btn.center = self.view.center;
    [self.btn setBackgroundColor:[UIColor blueColor]];
    [self.btn setTitle:@"按鈕" forState:UIControlStateNormal];
    [self.btn addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn];
    
    __weak typeof(self) weakSelf = self;
//    self.timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//        [weakSelf timerAction];
//    }];
    
    self.timer =  [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timerAction) userInfo:nil repeats:YES];
    
    
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
//    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkAction)];
//    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)action
{
    NSLog(@"執(zhí)行點擊");
}
- (void)timerAction
{
    NSLog(@"執(zhí)行timer定時器");
}
- (void)displayLinkAction
{
    NSLog(@"執(zhí)行displayLink定時器");
}

- (void)dealloc
{
  [self.timer invalidate];
    NSLog(@"%s",__func__);
}

1.只打開TestBtn的方法,運行進入VC2,再POP回VC1,打印內(nèi)容


image.png

代表button和VC2沒有造成循環(huán)引用

2.只打開block類型的timer代碼,并重新進行上面的操作

    self.timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self timerAction];
    }];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
image.png

回到VC1時,timer還在執(zhí)行,并且VC2也沒銷毀,造成了循環(huán)引用
VC2->timer->timer的block對[self timerAction]變量捕捉VC2,造成了循環(huán)引用,可以通過__weak對[self timerAction]的捕捉VC2為弱引用

    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf timerAction];
    }];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

打印信息,顯示這樣就不會造成循環(huán) 引用


image.png

但是有其他情況,比如不是通過block捕捉的self,而是通過target引用的,那么__weak就用不了了,比如這樣,我試過了VC2不會銷毀

    __weak typeof(self) weakSelf = self;
    self.timer =  [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

這種可以通過新建一個類,然后VC2->強timer->新建類強引用->弱VC2的方式進行解決,我這里新建了一個類TestProxy

@interface TestProxy : NSObject

@property(nonatomic,weak)id target;

+ (instancetype)proxyWithTarget:(id)target;

@end
@implementation TestProxy

+ (instancetype)proxyWithTarget:(id)target
{
    TestProxy *proxy = [[TestProxy alloc] init];
    proxy.target = target;
    return proxy;
}

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    return _target;
}

然后修改self.timer的創(chuàng)建方式

    self.timer =  [NSTimer scheduledTimerWithTimeInterval:1 target:[TestProxy proxyWithTarget:self] selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

打印結(jié)果為,證明也是可以銷毀的


image.png

但是上面的內(nèi)容可以再優(yōu)化,由于TestProxy繼承自NSObject,它需要經(jīng)過消息發(fā)送的遍歷查找,動態(tài)解析,最后才會到我們這里的消息轉(zhuǎn)發(fā)過程,大大消耗性能;蘋果提供了一個專門做消息轉(zhuǎn)發(fā)的類NSProxy,這個類和NSObject同一級別,該類的特性就是去掉消息遍歷查找,消息添加,直接消息轉(zhuǎn)發(fā)的過程,大大提高了效率

@interface GYJProxy : NSProxy

+ (instancetype)proxyWithTarget:(id)target;

@end
@interface GYJProxy ()

@property(nonatomic,weak)id target;

@end
@implementation GYJProxy

+ (instancetype)proxyWithTarget:(id)target
{
    GYJProxy *proxy = [GYJProxy alloc];
    proxy->_target = target;
    return proxy;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    return [_target methodSignatureForSelector:sel];
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
    [invocation invokeWithTarget:_target];
}
@end

最后驗證的結(jié)果也是可以正常銷毀的,CADisplayLink和NSTimer一樣,也會造成循環(huán)引用,處理方式和NSTimer一樣.還有就是NSTimer和CADisplayLink都是基于runloop使用的,這會造成時間稍微不準,建議采用GCD的定時器,GCD的定時器不依賴runloop,時間是準的

    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    //1.源 2.開始時間 3.間隔時間 4.精準度
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, NSEC_PER_SEC*1.0, 0*NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        NSLog(@"定時器執(zhí)行的任務");
    });
    dispatch_resume(timer);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市称簿,隨后出現(xiàn)的幾起案子扣癣,更是在濱河造成了極大的恐慌,老刑警劉巖憨降,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件父虑,死亡現(xiàn)場離奇詭異,居然都是意外死亡授药,警方通過查閱死者的電腦和手機士嚎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進店門呜魄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人莱衩,你說我怎么就攤上這事爵嗅。” “怎么了膳殷?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長九火。 經(jīng)常有香客問我赚窃,道長,這世上最難降的妖魔是什么岔激? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任勒极,我火速辦了婚禮,結(jié)果婚禮上虑鼎,老公的妹妹穿的比我還像新娘辱匿。我一直安慰自己,他們只是感情好炫彩,可當我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布匾七。 她就那樣靜靜地躺著,像睡著了一般江兢。 火紅的嫁衣襯著肌膚如雪昨忆。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天杉允,我揣著相機與錄音邑贴,去河邊找鬼。 笑死叔磷,一個胖子當著我的面吹牛拢驾,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播改基,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼繁疤,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了秕狰?” 一聲冷哼從身側(cè)響起嵌洼,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎封恰,沒想到半個月后麻养,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡诺舔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年鳖昌,在試婚紗的時候發(fā)現(xiàn)自己被綠了备畦。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡许昨,死狀恐怖懂盐,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情糕档,我是刑警寧澤莉恼,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站速那,受9級特大地震影響俐银,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜端仰,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一捶惜、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧荔烧,春花似錦吱七、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至臀稚,卻和暖如春市袖,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背烁涌。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工苍碟, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人撮执。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓微峰,卻偏偏與公主長得像,于是被迫代替她去往敵國和親抒钱。 傳聞我的和親對象是個殘疾皇子蜓肆,可洞房花燭夜當晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容