Blocks and retain cycles

佐手、 提交于 2019-12-05 08:14:37

In both listings, you are referring to an instance variable, thus implicitly capturing self. A strong self.

This leads to a first solution to your problem:

int clients = _clients;
// use `clients` instead of `_clients` in your blocks

Alternatively, you can use a weak self:

id __weak weakself = self;
// use `weakself->_clients` in your blocks

The reason why you got the error in listing 1 is because the block captures self and the block is stored in an instance variable of the same self, leading to a retain cycle. Both solutions above will solve that issue.

There is a retain cycle in Listing 1 because in Listing1 self is retaining the ivar _callback in which you access an other ivar, _clients, and because _clients is a primitive var the block retains self to access it !

In Listing2, the block is retained by the queue and not by self.

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