What you want to avoid with blocks is a retain cycle—two objects keeping each other alive unnecessarily.
If I have an object with this property:
@property (strong) void(^completionBlock)(void);
and I have this method:
- (void)doSomething
{
self.completionBlock = ^{
[self cleanUp];
};
[self doLongRunningTask];
}
the block will be kept alive when I store it in the completionBlock property.
But since it references self inside
the block, the block will keep self alive
until it goes away—but this won’t happen since they’re both referencing each other.
In this method:
- (void)doSomething
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self cleanUp];
}];
[self doLongRunningTask];
}
you don’t need to make a weak reference to self.
The block will keep self alive,
since it references self from
within, but since all we’re doing is handing the block off to [NSOperationQueue
mainQueue], self isn’t
keeping the block alive.
本文探讨了如何在Objective-C中通过使用NSOperationQueue来避免对象间的循环引用导致的内存泄漏问题,重点介绍了如何将操作块传递给队列,从而使得对象在任务完成后自动被释放。
1162

被折叠的 条评论
为什么被折叠?



