Skip to content

Instantly share code, notes, and snippets.

@elado
Created May 18, 2011 21:14
Show Gist options
  • Save elado/979577 to your computer and use it in GitHub Desktop.
Save elado/979577 to your computer and use it in GitHub Desktop.
Blocks with closures errors in Obj-C
@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
// app code:
// ################################
// refer instance in the block -
// ERROR on Block_copy(block);
// EXC_BAD_ACCESS
// debugger on: 0x000023b2 <+0050> add $0x18,%esp
// stack trace is on: Block_copy(block);
// ################################
TestClass *test1 = [[TestClass alloc] initWithBlock:^{
NSLog(@"TestClass %@", test1);
}];
[test1 exec];
[test1 release];
// ################################
// alloc instance BEFORE init
// NO ERROR
// ################################
TestClass *test2 = [TestClass alloc];
test2 = [test2 initWithBlock:^{
NSLog(@"TestClass %@", test2);
}];
[test2 exec];
[test2 release];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment