我已经测试了以下代码。
// Employee.h
@interface Employee : NSObject
@end
// Employee.m
@implement Employee
@end
// main.m
int main() {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
Employee* john = [[Employee alloc] init];
void (^print)(void) = ^{
NSLog(@"employee = %@", john);
}
[john release];
[pool release];
return 0;
}
我使用乐器跟踪了约翰的引用计数,但是约翰的引用计数似乎没有在打印块中增加。
我认为john应该被捕获并保留在打印块中。
我误解了什么?
答案 0 :(得分:1)
这里的块是基于堆栈的块。基于堆栈的块不保留本地上下文。
将块复制到堆中时将保留 john
(通过调用[print copy]
,并且不要忘记您需要release
或autorelease
阻止您复制)。
ARC知道何时必须复制和释放块,它将在必要时处理。你应该考虑使用它,这将使你的生活更容易处理块。
<小时/> 编辑
请改为尝试:
void (^print)(void) = [^{
NSLog(@"employee = %@", john);
} copy];
...
[print release];