本文主要是介绍IOS GCD定时器实现,UITableViewCell 上跑定时器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
浏览器搜索IOS GCD定时器会有超级多的文章写这个东西。今天自己实现了一个GCD定时器不用考虑其关闭界面界面或者使用者释放其自动释放。另UITableViewCell 跑定时器丝毫没有问题。核心代码如下
-(NSString *)addTimerWithTimeInterval:(NSTimeInterval)timeInterval
target:(id)target
selector:(SEL)selector
userInfo:(id)userInfo
repeats:(BOOL)repeats
fire:(BOOL)fire{
__block NSString *timerKey = [NSString stringWithFormat:@"%p%@%f%f",target,NSStringFromSelector(selector),timeInterval,[[NSDate date] timeIntervalSinceNow]];
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
[self.timerContainer setObject:timer forKey:timerKey];
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC));
uint64_t interval = (uint64_t)(timeInterval * NSEC_PER_SEC);
dispatch_source_set_timer(timer, start, interval, 0);
typeof(self) __weak weakSelf = self;
__weak id weakTarget = target;
dispatch_source_set_event_handler(timer, ^{
if (weakTarget && selector && [weakTarget respondsToSelector:selector]) {
IMP imp = [weakTarget methodForSelector:selector];
void (*func)(id, SEL,id) = (void *)imp;
func(weakTarget, selector,userInfo);
if (!repeats) {
dispatch_cancel(timer);
[weakSelf.timerContainer removeObjectForKey:timerKey];
}
}else{
dispatch_cancel(timer);
[weakSelf.timerContainer removeObjectForKey:timerKey];
}
});
if (fire) {
dispatch_resume(timer);
}
return timerKey;
}
Github 地址: https://github.com/ZXLBoaConstrictor/ZXLGCDTimer 用着还行的话给个star
这篇关于IOS GCD定时器实现,UITableViewCell 上跑定时器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!