Louie
Louie

Reputation: 5940

NSTimer on seperate thread so it doesnt tie up the UI Elements

I cant seem to find a suitable answer on SO or google.

I am hitting a web server for new data every 15 seconds. The problem is while waiting for a response from the server (a few seconds at times) my user interface is tied up. I cant seem to figure out how to start an NSTimer on a seperate thread so I can pull new data in the background, leaving my UI buttons responsive.

Any suggestions?

Thanks!

Upvotes: 1

Views: 1197

Answers (2)

Carter
Carter

Reputation: 3093

When you request from the server, you can use an asynchronous NSURLRequest to receive the data. Then, you could keep your NSTimer in the main thread, because all it would be doing is creating an asynchronous NSURLRequest every 15 seconds. Otherwise you can create a NSTimer in the background thread by creating the timer with

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats

Then add the timer to whatever run loop you want by calling

[[NSRunLoop currentRunLoop] addTimer:MY_TIMER forMode:NSDefaultRunLoopMode];

(Replace currentRunLoop with the run loop that you want the NSTimer to be in.)

Upvotes: 5

iandotkelly
iandotkelly

Reputation: 9134

There are various ways of working with threads, but GCD (Grand Central Dispatch) is probably the easiest.

Here is a tutorial example building a simple job queue in GCD.

Upvotes: 0

Related Questions