I got the this code in a class:
- (void)cancel {
if (_cancelBlock)
_cancelBlock();
}
- (void)overrideCancelWithBlock:(void(^)(void))cancelBlock {
[_cancelBlock release];
NSLog(@"AsyncOperation-overrideCancelWithBlock-[cancelBlock retainCount]=%lu (before)", [cancelBlock retainCount]);
_cancelBlock = [[cancelBlock copy] retain];
NSLog(@"AsyncOperation-overrideCancelWithBlock-[_cancelBlock retainCount]=%lu (after)", [_cancelBlock retainCount]);
}
- (void)dealloc
{
NSLog(@"AsyncOperation-dealloc-[_cancelBlock retainCount]=%lu (before)", [_cancelBlock retainCount]);
[_cancelBlock release];
NSLog(@"AsyncOperation-dealloc-[_cancelBlock retainCount]=%lu (after)", [_cancelBlock retainCount]);
[super dealloc];
}
The output for this NSLog()'s are:
AsyncOperation-overrideCancelWithBlock-[cancelBlock retainCount]=1 (before)
AsyncOperation-overrideCancelWithBlock-[_cancelBlock retainCount]=1 (after)
AsyncOperation-dealloc-[_cancelBlock retainCount]=1 (before)
AsyncOperation-dealloc-[_cancelBlock retainCount]=1 (after)
The documentation for the copy
method says this:
Special Considerations
If you are using managed memory (not garbage collection), this method retains the new object before returning it. The invoker of the method, however, is responsible for releasing the returned object.
So. Way the output of the NSLog() always show the same value for retainCount
?
That over-retains the block; just -copy it.
Since Blocks can change form at runtime based upon actions taken and change type at compile time based on implementation details, the various Block classes generally treat
retainCount
as the nonsense generator that it is. In some cases, this will mean returning 1 always.Note that a
retainCount
of zero is a logical impossibility in all cases.and the documentation for
retainCount
says this:To answer your question: Only apple might know why the retainCount at this point is like it is.