Run method on main thread from another thread

user531461 picture user531461 · Feb 3, 2011 · Viewed 12k times · Source

My model class has to get some data from the internet. So I decided to run it on another thread so the ui doesn't freeze. So when an object wants some data it first asks the model using a method of this type:

- (void)giveMeSomeData:(id)object withLabel:(id)label {
objectAsking= object;
theLabel= label;
NSThread* thread= [[NSThread alloc] initWithTarget:self selector:@selector(getTheDataFromInternet) object:nil];
[thread start];
}

- (void)getTheDataFromInternet {
//getting data...

theData= [dataFromInternet retain]; //this is the data the object asked for
[self returnObjectToAsker];
}

- (void)returnObjectToAsker {
[objectAsking receiveData:theData withLabel:theLabel];
}

As I'm still a newbie, can you tell me if it's a good pattern?

Thanks!

Answer

Dave DeLong picture Dave DeLong · Feb 3, 2011

Your setup is pretty much correct. You never want to initiate any sort of network connection on the main thread.

As it currently stands, -returnObjectToAsker will be executed on the background thread.

You'd probably be interested in -[NSObject performSelectorOnMainThread:withObject:waitUntilDone:].

Or if you wanted to something with Grand Central Dispatch (iOS 4+, Mac OS X 10.6+), you could do:

#import <dispatch/dispatch.h>

- (void)giveMeSomeData:(id)object withLabel:(id)label {
    dispatch_async(dispatch_get_global_queue(0,0), ^{
      //this runs on a background thread
      //get data from the internet
      dataFromTheInternet = ...;
      dispatch_async(dispatch_get_main_queue(), ^{
        [object receiveData:dataFromTheInternet withLabel:label];
        //this runs on the main thread.  Use theData
      });
    });
}

Since the blocks capture their environment, you wouldn't even have to save off object and label into ivars. :)