Question

Block references as instance vars in Objective-C

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.

 45  20696  45
1 Jan 1970

Solution

 88

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];
2010-07-12

Solution

 12

Yes, you most certainly can store a reference to a (copy) of an Objective-C block. The variable declaration is a little bit hairy, like C function pointers, but beyond that it's no problem. For a block that takes and id and returns void:

typedef void (^MyActionBlockType)(id);

@interface MyClass : NSObject 
{

}

@property (readwrite,nonatomic,copy) MyActionBlockType myActionBlock;
@end

will do the trick.

2010-07-12