iphonecocoa-touchios4nsthread

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 to 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.


Solution

  • 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.