以下 GCD / 块场景的推荐模式是什么?
我有一个关于 Grand Central Dispatch、块和内存管理的问题。考虑以下代码:
Worker *myWorker = [[Worker alloc] init];
[work doAsyncStuffWithBlock:^(NSMutableDictionary *info)
{
NSLog(@"processing info results");
}];
[myWorker release];
在这里,我希望 doAsyncStuffWithBlock 异步发生,然后在有一些结果时执行该块。同时这个主要代码还会继续。在这里释放 myWorker 安全吗?我在内部实现的dispatch_queue是否会保留它的引用以最终执行该块?或者,我应该在块内释放它吗?这看起来很奇怪。感谢您的任何建议。
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 block? that seems weird. Thanks for any suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当一个块引用一个 Objective-C 对象时,例如:
它会自动保留该对象,并且当块被释放时,它会自动释放该对象。
所以,是的,您应该在代码中释放
myWorker
,不,您不应该在块内释放myWorker
。When a block references an Objective-C object, e.g.:
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 releasemyWorker
inside the block.阅读
你可以在块外释放。
Read
You can release outside the block.