Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

objective c - iOS4 Create Background Timer

I (Basically) need to create a background timer on iOS 4 that will allow me to execute some code when a specific amount of time has passed. I have read that you can accomplish this using some [NSThread detachNewThreadSelector: toTarget: withObject:]; but how does that work in practice? How can I ensure that the thread remains in the background also. Local notifications will NOT work for me, as I need to execute code, not notify the user.

Help would be appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can also do this using Grand Central Dispatch (GCD). This way you can use blocks to keep your code in one place, and be sure you're calling the main thread again if you need to update your UI after you've finished background processing. Here's a basic example:

#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) reference: http://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html

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

Background Task reference: http://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/UIApplication/beginBackgroundTaskWithExpirationHandler:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...