1.用timer的话 vc没有了 timer也跟着释放了 如果不释放 那就成循环引用了
2.用本地通知的话,只能设置固定时间为触发时间,不能像定时器那样每隔一段时间执行一次
PHPz2017-04-18 09:53:38
It is recommended to use GCD’s timer. GCD's timer is different from NSTimer. NSTimer is affected by RunLoop, but GCD's timer is not affected because RunLoop is also based on GCD.
-(void) startGCDTimer{
// GCD定时器
static dispatch_source_t _timer;
NSTimeInterval period = 1.0; //设置时间间隔
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
// 事件回调
dispatch_source_set_event_handler(_timer, ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Count");
});
});
// 开启定时器
dispatch_resume(_timer);
// 关闭定时器
// dispatch_source_cancel(_timer);
}
黄舟2017-04-18 09:53:38
It’s up to you how to use it, please analyze the specific situation.
Personal best practice is Runloop
,新建一个类,类初始化实例之后新建一个线程,监听这个线程的Runloop
消息,添加信号源,然后在回调的方法里实现你的需求. 这样可以避免一些NSTimer
error or other issues.
The second one is monitoringCADisplayLink
,当然,监听CADisplayLink
, which also has hidden dangers. It may cause "frame drops" due to heavy workload.
By the way, it’s not easy to implement in the background unless you register 音频服务
. You can also study this method:
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIApplication : UIResponder
/*! The system guarantees that it will not wake up your application for a background fetch more
frequently than the interval provided. Set to UIApplicationBackgroundFetchIntervalMinimum to be
woken as frequently as the system desires, or to UIApplicationBackgroundFetchIntervalNever (the
default) to never be woken for a background fetch.
This setter will have no effect unless your application has the "fetch"
UIBackgroundMode. See the UIApplicationDelegate method
`application:performFetchWithCompletionHandler:` for more. */
- (void)setMinimumBackgroundFetchInterval:(NSTimeInterval)minimumBackgroundFetchInterval NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED;
@end