How to store blocks in properties in Objective-C?

Objective CObjective C-Blocks

Objective C Problem Overview


I'd like to store objective-c block in a property for later use. I wasn't sure how to do it so I googled a bit and there is very little info about the subject. But I've managed to find the solution eventually and I've thought that it might be worth sharing for other newbies like me.

Initially I've thought that I would need to write the properties by hand to use Block_copy & Block_release.

Fortunately I've found out that blocks are NSObjects and - copy/- release is equivalent to Block_copy/Block_release. So I can use @property (copy) to auto generate setters & getters.

Objective C Solutions


Solution 1 - 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();

Solution 2 - Objective C

Alternatively, without the typedef

@property (copy, nonatomic) void (^selectionHandler) (NSDictionary*) ;

Solution 3 - Objective C

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPiotr CzaplaView Question on Stackoverflow
Solution 1 - Objective CDave DeLongView Answer on Stackoverflow
Solution 2 - Objective CSteven KramerView Answer on Stackoverflow
Solution 3 - Objective CJorge PerezView Answer on Stackoverflow