Find yourself creating NSOperation subclasses frequently? Here’s a handy helper for you:
And speaking of that blog, it’s got a couple other NSOperation goodies as well:
…. One common network activity is search-as-you-type, in this case you need to also cancel the previous operation if it has not yet been completed, so lets built this behavior into the generic solution as well.
What we want is an subclass of NSOperation that provides a future result, lets call this class CWFutureOperation. It is abstract, so users are supposed to subclass and implement main method just as for NSOperation, only difference is that the main method implementation must call setResult: before exiting.
The result that is set in the main method implementation can then be fetched using the blocking method result, equivalent to get() from the Java Future. As an alternative we would also like to be handed the method upon completion via a target-action pair. If the target-action pair is only called for finished operations that are not cancelled, then we get the search-as-you-type behavior for free…
That’s some handy design guidance there, yep; and also check out his
which has handy wrapper conveniences for NSInvocationOperation and a shared global queue.
Aaaand to finish up, wondering why your NSURLConnection operations suddenly stopped working? Here’s why:
… Seems like Apple has made a change where in if the NSURLConnection’s initWithRequest method is called from a thread that’s not the main thread, it doesn’t start downloading the URL contents immediately. The bug fix for this issue is fortunately simple…
And it’s just calling -performSelectorOnMainThread to start from the background operation. Now you know!
NSOperationStack: A LIFO (Last-In, First-Out) queuing extension for NSOperationQueue