views:

64

answers:

1

I've defined a class called 'AsyncNetworkOperation', a subclass of NSOperation used to perform database queries in my app. My AsyncNetworkOperation class has a protocol, to be used by objects that initiate the AsyncNetworkOperation:

@protocol AsyncNetworkOperationDelegate
@optional - (void)operationAboutToFinish;
@required - (void)operationFinishedWithData:(id)retrievedData;
@required - (void)operationFinishedWithError:(NSError*)error;
@end

This all works fine, except in the case where the delegate I'm calling back to wants to show a UIAlertView, start an NSTimer, or do something else that secondary threads either aren't supposed to do, or require extra effort to do.

So here's my question: when I callback to the delegate, should I do so via -[NSObject performSelectorOnMainThread:]? It would seem that in doing so, I relieve my delegate from the burden of having to know whether it's being called back via a secondary or primary thread, thereby allowing it to implement functionality in the most straightforward way possible, with no limitations.

Just wondering about the standard way to approach this problem.

Thanks.

A: 

I would recommend having the AsyncNetworkOperation call the delegate object in the same thread that it was invoked on. So if the async operation was first invoked on the main thread, then it should call the delegate on the main thread!

You can imagine future use where the delegate doesn't need to update the UI and calling it from a secondary thread would be good.

notnoop
What's the best way to do this? My best guess: 1) When the async operation is started, call +[NSThread currentThread] to get the thread the operation was invoked on. Store in an instance variable. 2) When the operation is done, call the delegate using -[NSObject performSelector:onThread:withObject:waitUntilDone:], passing the stored thread via the onThread: parameter. Does this seem correct, or is there a cleaner way of doing this? Thanks.
Greg Maletic
@Greg, this sounds about right, if you are actually creating threads yourself. Otherwise, it may not be needed.
notnoop
I'm simply instantiating an NSOperation and adding it to an NSOperationQueue. Is that what you mean by "creating threads yourself"? (I ask this only because some Cocoa documentation almost seems to imply that using NSOperation is a way to get around creating threads...when my understanding of the true way it works is that NSOperationQueue creates a thread for me.)
Greg Maletic