The question is, is it possible to create a canceled NSBlockOperation . As this answer suggests, citing the WWDC 2012 session # 211, creating parallel user interfaces , you certainly can.
However, this approach consists of limitations. It is noteworthy that you must put the undo logic in your block. This works fine if your block runs some loop in which it can repeatedly check the status of isCancelled . But if you are in the middle of some kind of network request, it will be inconvenient to execute in NSBlockOperation .
Using the template described in this other answer (and in this WWDC 2012 video), you can write NSBlockOperation , which used a tortured combination of NSURLSession -based NSURLSession and a polling cycle that cancels the NSURLSessionTask if the operation is canceled, which does what you intend , but this is a terrible decision (inefficient, cumbersome, burdening your application code with undo logic in a block, etc.).
If you want to do a NSOperation transaction, subclassing NSOperation will be a much more elegant way to do this. The first time you do this, it will seem cumbersome, but as soon as you become familiar with the template, it will become second nature and trivial to implement. And you return again and again to this pattern. See the section Defining a User-Defined Work Object in the Operation Queues section of the Concurrency Programming Guide for discussions on cancellation, simultaneous operations, in particular the discussion “Responding to Cancellation Events”.
As a final note, you describe these “usage blocks” and NSOperation -subclass as an “either / or” clause. Often, however, you actually go beyond two methods by creating a subclass of NSOperation that accepts block parameters that indicate what you want to do when loading is done. See AFNetworking for a great example of how to marry NSOperation blocks and subclass.
source share