Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C : Start an object on a background thread -- interact as usual?

I would like to have an object be callable from the main thread

MyObj* backgroundObject = [[MyObj alloc] initInBackground];
BOOL result = [backgroundObject computeResult];

But have all the methods of backgroundObject compute in another thread.

And also have backgroundObj be able to send messages to it's delegate. How can I do such a thing? Is it possible?

like image 726
DevDevDev Avatar asked Mar 10 '10 19:03

DevDevDev


1 Answers

As others have pointed out, an NSObject doesn't exist on any one thread, a thread only comes into play when you start executing its methods.

My suggestion would be to not use manual threads for every time that a method is called on the object, but instead use NSOperations and an NSOperationQueue. Have an NSOperationQueue as an instance variable of the object, and have calls to the various methods on the object create NSOperations which are inserted into the queue. The NSOperationQueue will process these operations on a background thread, avoiding all of the manual thread management you would need to have for multiple accesses to methods.

If you make this NSOperationQueue have a maximum concurrency count of 1, you can also avoid locking shared resources within the object between the various operations that will be performed on a background thread (of course you'll still need to lock instance variables that can be accessed from the outside world).

For callbacks to delegates or other objects, I'd recommend using -performSelectorOnMainThread:withObject:waitUntilDone so that you don't have to think about making those delegate methods threadsafe.

See the Concurrency Programming Guide for more.

like image 55
Brad Larson Avatar answered Oct 03 '22 08:10

Brad Larson