What is a simple rule to avoid objective-c block retain cycle memory leaks?

廉价感情. 提交于 2019-12-05 18:51:04

A retain cycle is when A -> B -> A (where -> means retains). It's bad because we cannot deallocate retained things, so the only way to deallocate A is to deallocate B, but that depends on deallocating A.

A block retain cycle is no different, except blocks are more aggressive about retaining: They retain any object referenced within them, so if A -> Block and Block mentions A, then A -> Block -> A.

All this leads to a simple rule when coding blocks. Consider all of the objects mentioned in the block and ask, do any of these objects retain this block? Most of the time they don't. But pay special attention to the object you're passing the block to, in other words:

[beSuspiciousOfMe heresABlock:^{
    NSLog(@"does %@ retain this block?", beSuspiciousOfMe];
}];

If you control beSuspiciousOfMe (which can be, and often is self), this is easy to check. If that code is opaque for some reason, and you're not sure, you can use the __weak copy trick.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!