Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store blocks in properties in Objective-C?

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.

like image 334
Piotr Czapla Avatar asked Nov 02 '10 20:11

Piotr Czapla


People also ask

How do blocks work in Objective-C?

Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary .

What is property in Objective-C?

Objective-C properties offer a way to define the information that a class is intended to encapsulate. As you saw in Properties Control Access to an Object's Values, property declarations are included in the interface for a class, like this: @interface XYZPerson : NSObject.


1 Answers

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(); 
like image 159
Dave DeLong Avatar answered Sep 22 '22 22:09

Dave DeLong