1.用timer的话 vc没有了 timer也跟着释放了 如果不释放 那就成循环引用了
2.用本地通知的话,只能设置固定时间为触发时间,不能像定时器那样每隔一段时间执行一次
PHPz2017-04-18 09:53:38
建議使用 GCD 的定時器。 GCD 的定時器和 NSTimer 是不一樣的,NSTimer 受 RunLoop 影響,但 GCD 的定時器不受影響,因為 RunLoop 也是基於 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
怎麼用看你啦,具體情況具體分析.
個人最佳實踐是Runloop
,新建一个类,类初始化实例之后新建一个线程,监听这个线程的Runloop
消息,添加信号源,然后在回调的方法里实现你的需求. 这样可以避免一些NSTimer
誤差或其他的問題.
第二個是監聽CADisplayLink
,当然,监听CADisplayLink
也是有隱患的,可能會因為任務量繁重造成"掉幀".
對了,在後台是不好實現的,除非註冊音频服务
. 還有你可以研究研究這個方法:
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