使用块回调时如何释放对象
这可能是关于内存管理的新手问题。
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
快速、不完整的答案:
[request autorelease]
这样做的问题是块隐式保留块体内引用的任何对象。因此,该块保留了
request
,而request
保留了该块,从而导致保留周期并且没有人被释放。为了解决这个问题,您可以将
request
变量声明为__block
,这可以防止块保留捕获的对象:推荐阅读:
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
, andrequest
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:Recommended reading: