以下 GCD / 块场景的推荐模式是什么?

发布于 2024-11-06 04:50:27 字数 403 浏览 0 评论 0原文

我有一个关于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烂柯人 2024-11-13 04:50:27

当一个块引用一个 Objective-C 对象时,例如:

Worker *myWorker = [[Worker alloc] init];
[work doAsyncStuffWithBlock:^(NSMutableDictionary *info)
{
    NSLog(@"processing info results");
    [myWorker doSomething];
}];
[myWorker release];

它会自动保留该对象,并且当块被释放时,它会自动释放该对象。

所以,是的,您应该在代码中释放 myWorker ,不,您不应该在块内释放 myWorker

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.

简单气质女生网名 2024-11-13 04:50:27

阅读

你可以在块外释放。

Read

You can release outside the block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文