I have a fairly simple, though expensive, task that I need to run in the background, which is the standard NSOperation situation. I also need to make sure the operation supports开发者_开发百科 cancellation, and stops appropriately. Given that requirement, which is the better approach: Just wrapping up the expensive method call in an NSInvocationOperation, or writing an NSOperation subclass from scratch?
Here's my thinking so far. NSInvocationOperations are my first choice, and are what I've used in the past, because the task is so simple that I don't want to write a whole class with all the NSOperation boilerplate code just to execute it. What now makes me hesitate is the fact that there doesn't really seem to be a way for an method executed in an NSInvocationOperation to check for cancellation that doesn't set off the hackery alarm in my head. See this question for some examples of said hackery. I've tried them, and they do work, they just also feel icky.
Writing an NSOperation subclass, as mentioned before, seems like overkill to perform the simple task, but there is no doubt that checking for cancellation is more elegant than anything I've come across for NSInvocationOperation.
So, for those who have more NSOperations under their belt, which have you used to the most successful end? Is there a nice cancellation solution using NSInvocationOperations that I may have missed? Without some sort of support for cancellation, the number of situations where NSInvocationOperations are useful just went off a cliff.
Subclassing NSOperation is the only elegant way to do this, I believe.
I tend only to use NSInvocationOperations when I'm refactoring existing code to be multithreaded, then it's a handy shortcut.
just subclass NSOperation. (more characters required)
精彩评论