iOS4创建后台计时器

Ric*_*III 3 objective-c ios4 localnotification background-thread

我(基本上)需要在iOS 4上创建一个后台计时器,这将允许我在经过特定时间后执行一些代码.我已经读过你可以用一些来完成这个[NSThread detachNewThreadSelector: toTarget: withObject:];但是在实践中它是如何工作的?如何确保线程也保留在后台.本地通知将为我工作,因为我需要执行代码,不通知用户.

帮助将不胜感激!

mrw*_*ker 20

您也可以使用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];
    });
}); 
Run Code Online (Sandbox Code Playgroud)

Grand Central Dispatch(GCD)参考:http: //developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html

块参考:http: //developer.apple.com/library/ios/#featuredarticles/Short_Practical_Guide_Blocks/index.html%23//apple_ref/doc/uid/TP40009758

后台任务参考: http://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/UIApplication/beginBackgroundTaskWithExpirationHandler:

  • 怎么停止这个GCD计时器 (3认同)