块中的retainCount显示外部行为 [英] retainCount in blocks show extrange behavior
本文介绍了块中的retainCount显示外部行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个班级得到了这段代码:
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];
}
此NSLog()的输出为:
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)
copy
方法的文档说:
特殊注意事项
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.
所以.这样,NSLog()的输出对于retainCount
总是显示相同的值?
So. Way the output of the NSLog() always show the same value for retainCount
?
推荐答案
查看全文