block is likely to lead a retain cycle [duplicate]

五迷三道 提交于 2019-12-01 08:58:05

To distill what others have written here:

  1. Neither code example creates a long-lasting retain cycle of the sort that will strand memory.
  2. Xcode complains about your addAsynchronousOperationWithBlock method because it has a suspicious name. It doesn't complain about addOperationWithBlock because it has special knowledge about addOperationWithBlock that overrides its suspicions.
  3. To get rid of the warning, use __weak (see the answers by jszumski and matt) or rename addAsynchronousOperationWithBlock to not start with "add" or "set".

To elaborate a bit on these:

  1. If self owns _queue, you will have a short-lived retain cycle. self will own _queue, which will own the blocks, and the block that calls [self foo:] will own self. But once the blocks have finished running, _queue will release them, and the cycle will be broken.

  2. The static analyzer has been programmed to be suspicious of method names starting with "set" and "add". Those names suggest that the method may retain the passed block permanently, possibly creating a permanent retain cycle. Thus the warning about your method. It doesn't complain about -[NSOperationQueue addOperationWithBlock:] because it's been told not to, by someone who knows that NSOperationQueue releases blocks after running them.

  3. If you use __weak the analyzer won't complain because there won't be the possibility of a retain cycle. If you rename your method the analyzer won't complain because it won't have any reason to suspect your method of permanently retaining the block passed to it.

When you use self within a block, it is captured by the block and could lead to a retain cycle. To cycle occurs when self (or something it has a strong reference to) has a strong reference to the block. To avoid the potential cycle, declare a weak pointer and use that in the block instead:

YourClassName * __weak weakSelf = self;

[_queue addAsynchronousOperationWithBlock:^(block signal) {
    [weakSelf foo:nil];
}];

The answer from jszumski is correct in essence, but it is important to get the form of the "weak self" dance correct. The form (building on his code) is:

YourClassName * __weak weakSelf = self;

[_queue addAsynchronousOperationWithBlock:^(block signal) {
    YourClassName * strongSelf = weakSelf;
    if (strongSelf)
         [weakSelf foo:nil];
}];

Thus we capture weakSelf through a strong reference. If you don't do that, weakSelf can go out of existence while you are in the middle of using it (because your reference to it is weak).

See my book for the dance, and for other things you can do about potential retain cycles caused by blocks:

http://www.apeth.com/iOSBook/ch12.html#_unusual_memory_management_situations

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