Block references as vars instances in Objective-C

I was wondering if it is possible to save 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.

+44
objective-c objective-c-blocks
Jul 12 '10 at 16:30
source share
2 answers

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]; 
+86
Jul 12 2018-10-12T00:
source share
— -

Yes, you can certainly keep a reference to a (copy) of the Objective-C block. A variable declaration is a little hairy, like C function pointers, but other than that, it's not a problem. For a block that takes id and returns void:

 typedef void (^MyActionBlockType)(id); @interface MyClass : NSObject { } @property (readwrite,nonatomic,copy) MyActionBlockType myActionBlock; @end 

will do the trick.

+12
Jul 12 2018-10-12T00:
source share



All Articles