Last Updated: March 18, 2016
· ryanmcgrath

Store an Objective-C block as a property

Blocks in Objective-C are quite useful - if you've lived in JavaScript (or Ruby, in which case I apologize) quite a bit, they'll feel a lot like anonymous functions or blocks in Ruby. If you want to store a reference to one for later use, though, it's not as apparent as some would expect it to be. There's two ways - the typedef method:

typedef void (^MyActionBlockType)(id);

@interface MyClass : NSObject { }

@property (nonatomic, copy) MyActionBlockType myActionBlock;

...which, I'm sorry, is just an eyesore and nowhere near as apparent as it could ideally be when you're just glancing at it. The more readable, succinct, and generally more awesome way to do it would be just storing it as a property, ala:

@property (nonatomic, copy) MyActionBlockType (^myActionBlock)();

When you're passing blocks around as arguments, it ends up being much easier to grok them being grouped in with properties and only properties - no lines needed elsewhere.

2 Responses
Add your response

Maybe I'm missing something but not sure how you can do this without the typedef. The second block of code alone won't compile.

over 1 year ago ·

The code without the typedef needs to have the return type specified as void (to match the example that uses the typedef):

@property (nonatomic, copy) void (^myActionBlock)();

Personally in this case I'd consider using a typedef, unless I was making a framework or other shared code and wanted to avoid introducing too many symbols into the shared namespace.

over 1 year ago ·