How to implement NSThread to constantly perform the function in background in iPhone SDK
In my iPhone app, I have to perform function constantly in background.
For that I think I will have to use NSThread to call the function and keep it executing in background.
I dont want t开发者_如何学Goo stall my app and hence I want to use NSThread to keep my Main Thread free for user interaction.
How should I implement NSThread to perform the function in background?
EDIT:
The function is for fetching the data from a web server every 20 seconds and updating the tables in my iPhone app based on the data that is fetched from the web server.
I'd look at an NSOperationQueue first.
I'm guessing that your background task is really a small task repeated again and again. Make this into an NSOperation subclass and just add them onto an NSOperationQueue. That way you can control the background tasks more easily.
You also get the advantage with an NSOperationQueue that when there are no operations to run, the processor isn't just stuck in a while(YES) loop, waiting. This will help your app's UI be more responsive and will help battery life :)
However, if your background task is a single long running task that just needs to be started and then ignored, performSelectorInBackground isn't too bad an idea.
Sounds like a bad idea, but it's very simple.
[self performSelectorInBackground:@selector(theMethod:) withObject:nil];
Just have a while(YES) in theMethod: and it will never stop executing.
EDIT:
Luckily for you it's just as simple to do something once every 20 seconds.
[NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(theMethod:) userInfo:nil repeats:YES];
This will execute theMethod: once every 20 seconds. I might also add that this is a much better idea.
you'll want to interact with the thread's run loop. if it's an NSThread, it is created automatically. thus, you are given access to the CF/NS-RunLoop - typically by calling + [NSThread currentRunLoop]
from the secondary thread.
in that case, you add a CF/NS-Timer to the run loop, and let it run and repeat until your work is finished. when the timer fires, your thread is awoken, and you then do your work.
精彩评论