How to store blocks in properties in Objective-C?
Edit: updated for ARC
typedef void(^MyCustomBlock)(void);
@interface MyClass : NSObject
@property (nonatomic, copy) MyCustomBlock customBlock;
@end
@implementation MyClass
@end
MyClass * c = [[MyClass alloc] init];
c.customBlock = ^{
NSLog(@"hello.....");
}
c.customBlock();
Alternatively, without the typedef
@property (copy, nonatomic) void (^selectionHandler) (NSDictionary*) ;
You can find a very good explanation of this in WWDC 2012 session 712 starting in page 83. The correct way of saving a block under ARC is the following:
@property(strong) my_block_type work;
Be careful with the retain cycles. A good way to solve is set the block to nil when you do not need it anymore:
self.work = nil;