天天看點

使用block優化NSTimer——筆記

《Effective Objective-C 2.0  編寫高品質iOS與OS X代碼的52個有效方法》(第五十二條:别忘了NSTimer會保留其目标對象)筆記

要點如下:

1、計時器隻有放在運作循環中,才能正常觸發任務

2、建立計時器:

+ (NSTimer *)scheduledTimerWithTimeInterval: 
    (NSTimerInterval)seconds //時間間隔
    target:(id)target //NSTimer會保留target
    selector: (SEL)selector //回調方法
    userInfo: (id)userInfo //回調selector時所帶的參數
    repeats: (BOOL)repeats; //是否反複執行。為NO隻執行一次且計時器自動停止,為YES需要手動調用invalidate停止
    
           
由于NSTimer會保留target,是以會導緻”保留環“,因為target一般是self,而建立的定時器一般會被self所保留(作為self的屬性)

3、用block解決”保留環“問題:

首先給NSTimer添加分類EOCBlocksSupport。

NSTimer+EOCBlocksSupport.h

+ (NSTimer *)eoc_scheduledTimerWithTimeInterval: (NSTimeInterval)interval  block:(void (^) ())block  repeats:(BOOL)repeats;
           

NSTimer+EOCBlocksSupport.m

+ (NSTimer *)eoc_scheduledTimerWithTimeInterval: (NSTimeInterval)interval  block:(void (^) ())block  repeats:(BOOL)repeats{
    return [self scheduledTimerWithTimeInterval:interval
                    target:self
                    selector:@selector(eoc_blockInvoke:)
                    userinfo:[block copy] 
                    repeats:repeats
            ];
}


+ (void)eoc_blockInvoke:(NSTimer *)timer{
    void (^block)() = timer.userinfo;
    if(block){
        block();
    }
}
           

建立NSTimer:

#import "NSTimer+EOCBlocksSupport.h"

...

- (void)createTimer{
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer eoc_scheduledTimerWithTimeInterval:5.0f
                            block: ^{
                                [weakSelf doSomething];
                            }
                            repeats: YES];
}
           
注:對block的了解,可參考:https://blog.csdn.net/u012773581/article/details/87795894
上一篇: NSTimer 使用