我(基本上)需要在 iOS 4 上创建一个后台计时器,它允许我在经过特定时间后执行一些代码。我已经读到您可以使用一些来完成此操作[NSThread detachNewThreadSelector:
toTarget:
withObject:];
,但在实践中它是如何工作的?如何确保线程也保留在后台。本地通知对我不起作用,因为我需要执行代码,而不是通知用户。
帮助将不胜感激!
我(基本上)需要在 iOS 4 上创建一个后台计时器,它允许我在经过特定时间后执行一些代码。我已经读到您可以使用一些来完成此操作[NSThread detachNewThreadSelector:
toTarget:
withObject:];
,但在实践中它是如何工作的?如何确保线程也保留在后台。本地通知对我不起作用,因为我需要执行代码,而不是通知用户。
帮助将不胜感激!
您也可以使用 Grand Central Dispatch (GCD) 执行此操作。这样,您可以使用块将代码保存在一个位置,并确保在完成后台处理后需要更新 UI 时再次调用主线程。这是一个基本示例:
#import <dispatch/dispatch.h>
…
NSTimeInterval delay_in_seconds = 3.0;
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, delay_in_seconds * NSEC_PER_SEC);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
UIImageView *imageView = tableViewCell.imageView;
// ensure the app stays awake long enough to complete the task when switching apps
UIBackgroundTaskIdentifier taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:{}];
dispatch_after(delay, queue, ^{
// perform your background tasks here. It's a block, so variables available in the calling method can be referenced here.
UIImage *image = [self drawComplicatedImage];
// now dispatch a new block on the main thread, to update our UI
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = image;
[[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
});
});
Grand Central Dispatch (GCD) 参考:http: //developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
您可以使用这些调用在新线程 (detachNewThred) 中使用某些参数 (withObject) 执行对象 (toTarget) 的方法 (选择器)。
现在,如果您想执行延迟任务可能是最好的方法performSelector: withObject: afterDelay:
,如果您想在后台运行任务,请调用detachNewThreadSelector: toTarget: withObject:
这些建议的方法是否仅在应用程序首先启用后台执行(使用 UIBackgroundMode)时才适用?
我假设如果应用程序不能合法地声称是 voip/music/location 感知应用程序,那么如果它实现了这里描述的内容,它在时间间隔到期时不会执行?