在以往的 iOS 版本中,我們?yōu)榱吮苊?NSTimer 的循環(huán)引用問題,一個比較常用的解決辦法是為 NSTimer 添加一個 category,新增傳入 block 類型參數(shù)的接口。分類內(nèi)部實現(xiàn)是將此 block 作為 NSTimer 的 userInfo 參數(shù)傳入,而 NSTimer的 target 則設置為 timer 自己。以此來避免 NSTimer 持有 VC。代碼如下:
// NSTimer+BlocksSupport.h
#import <Foundation/Foundation.h>
@interface NSTimer (BlocksSupport)
+ (NSTimer *)ly_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
repeats:(BOOL)repeats
block:(void(^)())block;
@end
// NSTimer+BlocksSupport.m
#import "NSTimer+BlocksSupport.h"
@implementation NSTimer (BlocksSupport)
+ (NSTimer *)ly_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
repeats:(BOOL)repeats
block:(void(^)())block;
{
return [self scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(ly_blockInvoke:)
userInfo:[block copy]
repeats:repeats];
}
+ (void)ly_blockInvoke:(NSTimer *)timer {
void (^block)() = timer.userInfo;
if(block) {
block();
}
}
@end
而在 iOS 10 之后,蘋果終于為 NSTimer 添加了一個官方 API,支持傳入 block 類型參數(shù)。可謂是千呼萬喚始出來。新官方 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));
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval
repeats:(BOOL)repeats
block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));