Block references as instance vars in Objective-C

Jacob Relkin picture Jacob Relkin · Jul 12, 2010 · Viewed 20k times · Source

I was wondering if it's possible to store a reference to an anonymous function (block) as an instance variable in Objective-C.

I know how to use delegation, target-action, etc. I am not talking about this.

Answer

Dave DeLong picture Dave DeLong · Jul 12, 2010

Sure.

typedef void(^MyCustomBlockType)(void);

@interface MyCustomObject {
  MyCustomBlockType block;
}
@property (nonatomic, copy) MyCustomBlockType block; //note: this has to be copy, not retain
- (void) executeBlock;
@end

@implementation MyCustomObject
@synthesize block;

- (void) executeBlock {
  if (block != nil) {
    block();
  }
}

- (void) dealloc {
  [block release];
  [super dealloc];
}
@end

//elsewhere:

MyCustomObject * object = [[MyCustomObject alloc] init];
[object setBlock:^{
  NSLog(@"hello, world!");
}];

[object executeBlock];
[object release];