Thomas Joulin
Thomas Joulin

Reputation: 6650

Manage the memory of objects calling a delegate callback block

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: ?

Upvotes: 1

Views: 212

Answers (1)

Kurt Revis
Kurt Revis

Reputation: 27994

No, ObjectA will not be deallocated at any moment -- it will be retained until ObjectB is done with the operation.

Probably -[ObjectB executeLongRequestThenDo:] will call Block_copy on the block. This will cause the block to be moved from the stack to the heap, and will retain all the NSObjects that the block directly references, namely self.

When ObjectB is done, it should run the block, then call Block_release, which will release self. Or, if you have some way of canceling the operation, ObjectB should 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.

Upvotes: 4

Related Questions