NSInteger _count;
NSTimer* _timer;
timer需要有消息循环。UI线程等调用
NSTimer在后台运行
更多 0
objective-c基础
这段代码可以放在- (void)applicationWillResignActive:(UIApplication )application或者- (void)applicationDidEnterBackground:(UIApplication )application 中,当然,当程序重新被激活的时候,需要将timer invalidate掉。
UIApplication *app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid) {
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
testTimer = [NSTimer scheduledTimerWithTimeInterval:(0.01) target:self selector:@selector(doSomeTest) userInfo:nil repeats:YES];
[testTimer fire];
[[NSRunLoop currentRunLoop] addTimer:testTimer forMode:NSRunLoopCommonModes];
[[NSRunLoop currentRunLoop] run];
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid) {
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
});
//该片段来自于http://outofmemory.cn
你看你是不是在主线程添加的timer 如果是异步线程的话,不能添加到currentRunloop 要添加到mainRunloop