我(基本上)需要在iOS 4上创建一个背景计时器,该计时器将使我在经过特定时间时执行一些代码。我读过,您可以使用一些 [NSThread detachNewThreadSelector: toTarget: withObject:]; 但是,这在实践中如何起作用?我如何确保线程也保留在后台。本地通知将 不是 为我工作,因为我需要执行代码,而不是通知用户。

帮助您将不胜感激!

有帮助吗?

解决方案

您可以使用这些调用来执行对象(totarget)的方法(选择器),并在新线程(distachNewThred)中使用一些参数(withObject)。

现在,如果您想执行延迟任务,最好的方法是 performSelector: withObject: afterDelay: 如果您想在背景上运行任务,请调用 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];
    });
}); 

大中央调度(GCD)参考:http://developer.apple.com/library/ios/#documentation/performance/Reference/gcd_libdispatch_ref/reference/reference/reference.html

块参考:http://developer.apple.com/library/ios/#featustrudarticles/short_practical_guide_blocks/index.html%23//apple_ref/doc/doc/uid/tp40009758

背景任务参考:http://developer.apple.com/library/ios/documentation/uikit/reference/uiapplication_class/reference/reference/reference.html#/apple_ref/apple_ref/appc/instm/uiapplication/uiapplication/beginback-withbackgroundtaskwithexpirationhexpirationhandler:

这些建议的方法首先仅在启用后台执行(使用UibackgroundMode)时才适用?

我认为,如果应用程序不能合法地声称是VoIP/Music/Location Aware App,那么如果它实现此处所述的内容,则时间间隔到期时将无法执行?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top