使用块回调时如何释放对象

发布于 2024-11-09 13:59:45 字数 702 浏览 0 评论 0原文

这可能是关于内存管理的新手问题。

在 Objective C 中使用块作为回调时如何释放对象?

(更新的代码)

@implementation ObjectWithCallback
- (void)dealloc {
    [_completionHandler release];
    [super dealloc];
}
- (void)doTaskWithCompletionHandler:(void(^)(void))handler {
    _completionHandler = [handler copy];
    // Start tasks...
}
- (void)tasksDone {
    // Do callback block
    _completionHandler();
    // Delete reference to block
    [_completionHandler release];
    _completionHandler = nil;
}

// Use of the ObjectWithCallback
ObjectWithCallback *request = [[ObjectWithCallback alloc] init];
[request doTaskWithCompletionHandler:^(void){
    // Callback called and task is ready.
}];

this is probably a newbie question regarding memory manegment.

How can i release an object when using blocks as callback in objective c?

(Updated code)

@implementation ObjectWithCallback
- (void)dealloc {
    [_completionHandler release];
    [super dealloc];
}
- (void)doTaskWithCompletionHandler:(void(^)(void))handler {
    _completionHandler = [handler copy];
    // Start tasks...
}
- (void)tasksDone {
    // Do callback block
    _completionHandler();
    // Delete reference to block
    [_completionHandler release];
    _completionHandler = nil;
}

// Use of the ObjectWithCallback
ObjectWithCallback *request = [[ObjectWithCallback alloc] init];
[request doTaskWithCompletionHandler:^(void){
    // Callback called and task is ready.
}];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

一绘本一梦想 2024-11-16 13:59:45

快速、不完整的答案:[request autorelease]

这样做的问题是块隐式保留块体内引用的任何对象。因此,该块保留了 request,而 request 保留了该块,从而导致保留周期并且没有人被释放。

为了解决这个问题,您可以将 request 变量声明为 __block,这可以防止块保留捕获的对象:

__block ObjectWithCallback *request = [[ObjectWithCallback alloc] init];

推荐阅读:

Quick, incomplete answer: [request autorelease]

The problem with this is that blocks implicitly retain any objects that are referenced inside the body of the block. So the block retains request, and request retains the block, leading to a retain cycle and nobody getting deallocated.

To remedy that, you declare your request variable as __block, which prevents the block from retaining the captured object:

__block ObjectWithCallback *request = [[ObjectWithCallback alloc] init];

Recommended reading:

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