I have a question about Grand Central Dispatch, blocks and memory management. Consider this code:
Worker *myWorker = [[Worker alloc] init];
[work doAsyncStuffWithBlock:^(NSMutableDictionary *info)
{
NSLog(@"processing info results");
}];
[myWorker release];
Here, I want the doAsyncStuffWithBlock to happen asynchronously and then perform the block when it has some results. Meanwhile this main code will continue on. Is it safe here to release myWorker? Will the dispatch_queue I implement internally keep a reference of it around to eventually execute that block? Or, should I release it inside the bl开发者_JAVA技巧ock? that seems weird. Thanks for any suggestions.
When a block references an Objective-C object, e.g.:
Worker *myWorker = [[Worker alloc] init];
[work doAsyncStuffWithBlock:^(NSMutableDictionary *info)
{
NSLog(@"processing info results");
[myWorker doSomething];
}];
[myWorker release];
it automatically retains that object and, when the block is released, it automatically releases that object.
So yes, you should release myWorker
in your code, and no, you shouldn’t release myWorker
inside the block.
Read
- this
- or this
You can release outside the block.
精彩评论