我一直在玩积木,遇到了一个奇怪的行为。这是接口/实现,它只包含一个能够执行它的块:
@interface TestClass : NSObject {
#if NS_BLOCKS_AVAILABLE
void (^blk)(void);
#endif
}
- (id)initWithBlock:(void (^)(void))block;
- (void)exec;
@end
@implementation TestClass
#if NS_BLOCKS_AVAILABLE
- (id)initWithBlock:(void (^)(void))block {
if ((self = [super init])) {
blk = Block_copy(block);
}
return self;
}
- (void)exec {
if (blk) blk();
}
- (void)dealloc {
Block_release(blk);
[super dealloc];
}
#endif
@end
虽然常规实例化和传递常规块有效:
TestClass *test = [[TestClass alloc] initWithBlock:^{
NSLog(@"TestClass");
}];
[test exec];
[test release];
使用引用正在创建的对象的块不会:
TestClass *test1 = [[TestClass alloc] initWithBlock:^{
NSLog(@"TestClass %@", test1);
}];
[test1 exec];
[test1 release];
错误是 EXC_BAD_ACCESS,Block_copy(block) 上的堆栈跟踪;调试器开启:0x000023b2 <+0050> add $0x18,%esp
我一直在玩,并将分配代码移到初始化上方,它起作用了:
TestClass *test2 = [TestClass alloc];
test2 = [test2 initWithBlock:^{
NSLog(@"TestClass %@", test2);
}];
[test2 exec];
[test2 release];
结合这两个片段也可以:
TestClass *test1 = [[TestClass alloc] initWithBlock:^{
NSLog(@"TestClass %@", test1);
}];
[test1 exec];
[test1 release];
TestClass *test2 = [TestClass alloc];
test2 = [test2 initWithBlock:^{
NSLog(@"TestClass %@", test2);
}];
[test2 exec];
[test2 release];
这里发生了什么?