Say I have a class ObjectA (a view controller for example), that does this :
ObjectB *objectB = [[ObjectB alloc] init];
[objectB executeLongRequestThenDo:^ (NSDictionary *results)
{
self.datasource = results;
[self.tableView reloadData];
}];
ObjectA can be deallocated at any moment, so I should be able to cancel the request of objectB, and tell it not to execute the block when its done, right ? Simply releasing it is not enough ? Also, should I call release just after executeLongRequestThenDo: ?
No,
ObjectAwill not be deallocated at any moment — it will be retained untilObjectBis done with the operation.Probably
-[ObjectB executeLongRequestThenDo:]will callBlock_copyon the block. This will cause the block to be moved from the stack to the heap, and will retain all theNSObjects that the block directly references, namelyself.When
ObjectBis done, it should run the block, then callBlock_release, which will releaseself. Or, if you have some way of canceling the operation,ObjectBshould similarly release the block.(It’s possible that ObjectB will do this all indirectly, by calling something that does the work, like
dispatch_async.)Reference: Blocks Programming Topics.
As for when you should release
objectB: it depends on whether it retains itself during the long-running operation, or not. To be safe, I would not release it until you know it’s fully complete, which would be at the end of your block, or after you’ve called its cancellation method.