NSTimer經(jīng)常會引起循環(huán)引用配紫,以下是幾種解決方案:
一:使用block的NSTimer,如下:
? ? __weak typeof(self) weakSelf = self;
? ? self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
? ? ? ? [weakSelftimerTest];
? ? }];
二:使用代理對象(NSProxy),自定義一個子類WPProxy繼承于NSProxy。代碼如下:
?創(chuàng)建timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[WPProxy proxyWithTarget:self] selector:@selector(xxx) userInfo:nil repeats:YES];
在創(chuàng)建的子類.m文件中實現(xiàn)以下方法:
+ (instancetype)proxyWithTarget:(id)target
{
? ? // NSProxy對象不需要調(diào)用init镐作,因為它本來就沒有init方法
? ? WPProxy*proxy = [WPProxy alloc];
? ? proxy.target= target; // target在點.h文件中定義藏雏,weak修飾屬性
? ? returnproxy;
}
- (NSMethodSignature*)methodSignatureForSelector:(SEL)sel
{
? ? return [self.target methodSignatureForSelector:sel];
}
- (void)forwardInvocation:(NSInvocation*)invocation
{
? ? [invocationinvokeWithTarget:self.target];
}
三?NSTimer依賴于RunLoop粪摘,如果RunLoop的任務(wù)過于繁重击喂,可能會導(dǎo)致NSTimer不準(zhǔn)時,GCD的定時器會更加準(zhǔn)時。代碼實現(xiàn)如下:
{
dispatch_queue_t queue = dispatch_queue_create("timer", DISPATCH_QUEUE_SERIAL);
? ??// 創(chuàng)建定時器
? ? dispatch_source_ttimer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
? ? dispatch_source_set_timer(timer,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? dispatch_time(DISPATCH_TIME_NOW,2 *NSEC_PER_SEC),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 1.0 *NSEC_PER_SEC,0);
? ? // 設(shè)置回調(diào)
? ? dispatch_source_set_event_handler(timer, ^{
? ? ????NSLog(@"1111");
? ??});
? ? // 啟動定時器
? ? dispatch_resume(timer);
}