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 thread. Because I reference my operation object from inside its own completion block, I’m using a __weak pointer to avoid a memory leak. However, the pointer is already set to nil by the time my code runs.
I’ve narrowed it down to this code sample. Anyone know where I went wrong, and the right way to accomplish this?
NSOperationSubclass *operation = [[NSOperationSubclass alloc] init];
__weak NSOperationSubclass *weakOperation = operation;
[operation setCompletionBlock:^{
dispatch_async( dispatch_get_main_queue(), ^{
// fails the check
NSAssert( weakOperation != nil, @"pointer is nil" );
...
});
}];
I’m not certain about this, but the correct way to do it is possibly to add __block to the variable in question, and then set it to nil at the end of the block to ensure that it is released. See this question.
Your new code would look like this: