views:

399

answers:

3

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?

+4  A: 

Sure, you can use NSThread for that, and have backgroundObject use performSelectorOnMainThread: to contact the delegate.

Carl Norum
Can you be more specific.
DevDevDev
@DevDevDev, about what? You need to create and use threads inside your `MyObj` methods, and then use `performSelector:` to make calls on the main thread; do you have some more specific questions?
Carl Norum
+1  A: 

Objects do not exist in threads AFAIK. The function you send to an object will always be performed on the thread you sent it from (unless you use NSThread or performSelectorOnMainThread or something along those lines).

Felix
+1  A: 

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.

Brad Larson