NSTimer

一 NSTimer的普通用法及其問題

用法

- (void)addNormalTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(logInfo:) userInfo:@"NormalTimer" repeats:YES];
}

- (void)logInfo:(NSTimer *)timer
{
    NSLog(@"logInfo %@", timer.userInfo);//logInfo NormalTimer
}

問題

當(dāng)從當(dāng)前界面跳轉(zhuǎn)到其他界面的時候控制臺還是源源不斷地在輸出logInfo NormalTimer,這說明NSTimer還在工作。

比較容易想到的方法就是在dealloc方法里添加invalidate方法

- (void)dealloc 
{
    [_timer invalidate];
    NSLog(@"dealloc");
}

再次運(yùn)行發(fā)現(xiàn)NSTimer還是沒有停止,dealloc方法也進(jìn)不來

分析一下為什么會出現(xiàn)這樣的問題

1 Runloop強(qiáng)引用了NSTimer對象

Note in particular that run loops maintain strong references to their timers, so you don’t have to maintain your own strong reference to a timer after you have added it to a run loop.

2 NSTimer對象強(qiáng)引用了target(示例中就是視圖控制器)

Target is the object to which to send the message specified by aSelector when the timer fires. The timer maintains a strong reference to target until it (the timer) is invalidated.

3 因?yàn)?code>target一直被強(qiáng)引用著,所以它不會被銷毀,也就不會觸發(fā)dealloc方法。

提到強(qiáng)引用自然會想到弱引用,如果把target設(shè)成弱引用,會不會就能解決問題呢?

- (void)addNormalTimer
{
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target: weakSelf selector:@selector(logInfo:) userInfo:@"NormalTimer" repeats:YES];
}

通過運(yùn)行發(fā)現(xiàn),使用弱引用也不能解決問題。這里weakstrong的唯一區(qū)別就是如果視圖控制器在NSTimer對象運(yùn)行期間被釋放了,NSTimer對象的target會變成nil。這里有更詳細(xì)的解釋

二 解決方法

方法1 : 提前調(diào)用invalidate方法

在合適的時候調(diào)用NSTimer對象的invalidate方法,比如在viewDidDisappear方法里面調(diào)用,但是viewDidDisappear方法有可能是在該視圖控制器pop的時候調(diào)用,也有可能是在push另外一個視圖控制器的時候調(diào)用。如果只是想在銷毀該視圖控制器之前(pop)讓NSTimer停止工作,那么可以在調(diào)用pop方法之前調(diào)用NSTimer對象的invalidate方法即可。

方法2 : 使用自定義類

既然不能通過weakSelf來解決問題,那么我們可以給NSTimer一個假的target,這個target有一個指向視圖控制器的弱引用,這樣的話視圖控制器就能被正常銷毀了。

示例中用到了2個類

  • JCAutoInvalidateTimer: 代替NSTimer類來創(chuàng)建NSTimer實(shí)例
  • JCAutoInvalidateTimerTarget: 前面提到的假target,由于這個類不需要調(diào)用者知道,所以沒有新建對應(yīng)的.h和.m文件,而是放到了JCAutoInvalidateTimer.m文件中
使用

1 使用下面的第一個方法會在合適的時間自動調(diào)用NSTimer的invalidate方法,所以使用起來非常簡單

[JCAutoInvalidateTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(logInfo:) userInfo:@"JCTimer" repeats:YES];

2 如果使用下面的第二個方法(帶block),由于JCAutoInvalidateTimerTarget對象沒有引用視圖控制器,也就無法知曉視圖控制器的生命周期,所以需要手動調(diào)用NSTimer對象的invalidate方法

- (void)addJCTimer
{   
    self.timer = [JCAutoInvalidateTimer scheduledTimerWithTimeInterval:1 block:^(id obj) {
        NSLog(@"logInfo %@", obj);
    } userInfo:@"JCTimer" repeats:YES];
}

- (void)dealloc
{
    [_timer invalidate];
    NSLog(@"dealloc");
}
源碼
@interface JCAutoInvalidateTimer : NSObject

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

/**
 需要在合適的時間和地點(diǎn)調(diào)用NSTimer對象的invalidate方法
 */
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
                                      block:(void (^)(id))block
                                   userInfo:(nullable id)userInfo
                                    repeats:(BOOL)yesOrNo;

@end
#import "JCAutoInvalidateTimer.h"

#pragma mark - JCAutoInvalidateTimerTarget

@interface JCAutoInvalidateTimerTarget : NSObject

@property(nonatomic, weak) id target;

@property(nonatomic, assign) SEL selector;

@property(nonatomic, weak) NSTimer *timer;

@end

@implementation JCAutoInvalidateTimerTarget

- (void)fire:(NSTimer *)timer
{
    if (self.target) {
        
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [self.target performSelector:self.selector withObject:timer.userInfo];
#pragma clang diagnostic pop
        
    } else {
        [self.timer invalidate];
    }
}

@end

#pragma mark - JCAutoInvalidateTimer


@implementation JCAutoInvalidateTimer

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
                                     target:(id)aTarget
                                   selector:(SEL)aSelector
                                   userInfo:(nullable id)userInfo
                                    repeats:(BOOL)yesOrNo
{
    JCAutoInvalidateTimerTarget *timerTarget = [JCAutoInvalidateTimerTarget new];
    timerTarget.target = aTarget;
    timerTarget.selector = aSelector;
    timerTarget.timer = [NSTimer scheduledTimerWithTimeInterval:ti
                            target:timerTarget
                                 selector:@selector(fire:)
                          userInfo:userInfo
                           repeats:yesOrNo];
    return timerTarget.timer;
}

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
                                      block:(void (^)(id))block
                                   userInfo:(nullable id)userInfo
                                    repeats:(BOOL)yesOrNo
{
    NSMutableArray *info = [NSMutableArray arrayWithObject:[block copy]];
    if (userInfo) {
        [info addObject:userInfo];
    }
    return [self scheduledTimerWithTimeInterval:ti
                                         target:self
                                       selector:@selector(blockInvoke:)
                                       userInfo:[info copy] repeats:yesOrNo];
}

+ (void)blockInvoke:(NSArray *)objects
{
    void (^block) (id);
    block = objects.firstObject;
    //userInfo為nil的檢查
    id info = nil;
    if (objects.count == 2) {
        info = objects.lastObject;
    }
    if (block) {
        block(info);
    } else {
        
    }
}


@end

三 參考鏈接

  1. weak-reference-to-nstimer-target-to-prevent-retain-cycle
  2. performselector-may-cause-a-leak-because-its-selector-is-unknown
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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