IPhone-SDK: calling a function in the background?

Is it possible to call my function in the background after a certain interval programmatically in the development of the iPhone SDK? I want to call one specific function in the background for specific periods of time (maybe every 10 minutes) while my application is running.

Could you share your ideas.

thanks.

Clav /

+4
source share
3 answers

The easiest way is to schedule NSTimer in the main thread of the loop. I suggest that the following code be implemented on application deletion, and you call setupTimer from applicationDidFinishLaunching:

 -(void)setupTimer; { NSTimer* timer = [NSTimer timerWithTimeInterval:10 * 60 target:self selector:@selector(triggerTimer:) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; } -(void)triggerTimer:(NSTimer*)timer; { // Do your stuff } 

If your material here takes a lot of time, and you cannot delay the main thread, then either call your things using:

 [self performSelectorInBackground:@selector(myStuff) withObject:nil]; 

Or you can run NSTimer in the background thread using something like this (I intentionally leak the stream object):

 -(void)startTimerThread; { NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(setupTimerThread) withObject:nil]; [thread start]; } -(void)setupTimerThread; { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NSTimer* timer = [NSTimer timerWithTimeInterval:10 * 60 target:self selector:@selector(triggerTimer:) userInfo:nil repeats:YES]; NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; [runLoop addTimer:timer forModes:NSRunLoopCommonModes]; [runLoop run]; [pool release]; } -(void)triggerTimer:(NSTimer*)timer; { // Do your stuff } 
+9
source

You may have a timer, look at NSTimer for what will work every 10 minutes so that it doesn't happen that in the background you have several options, for example, name 2. First of all, it should be noted that any work with the user interface is not must be executed in another thread, since UIKit is not thread safe.

NSThread link here http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html

NSTimer link here http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html

+5
source

To call a function in the main thread, use NSTimer.

To call it in another thread, create an NSOperation and configure NSOperationQueue to call it.

+2
source

All Articles