I\'m having difficulty converting some NSOperation code to ARC. My operation object uses a completion block, which in turn contains a GCD block that updates the UI on the main t
Another option would be:
NSOperationSubclass *operation = [[NSOperationSubclass alloc] init];
__weak NSOperationSubclass *weakOperation = operation;
[operation setCompletionBlock:^{
NSOperationSubclass *strongOperation = weakOperation;
dispatch_async(dispatch_get_main_queue(), ^{
assert(strongOperation != nil);
...
});
}];
[operationQueue addOperation:operation];
I assume you also add operation object to an NSOperationQueue. In that case, the queue is retaining an operation. It is probably also retaining it during execution of the completion block (although I haven't found official confirmation about the completion block).
But inside you completion block another block is created. That block will be run at some point in time later, possibly after NSOperations's completion block is run to an end. When this happens, operation
will be released by the queue and weakOperation
will be nil
. But if we create another strong reference to the same object from operation's completion block, we'll make sure operation
will exist when the second block is run, and avoid retain cycle because we don't capture operation
variable by the block.
Apple provides this example in Transitioning to ARC Release Notes see the last code snippet in Use Lifetime Qualifiers to Avoid Strong Reference Cycles section.