To distill what others have written here:
- Neither code example creates a long-lasting retain cycle of the sort
that will strand memory.
- 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.
- 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:
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.
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.
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.