Can I use Objective-C blocks as properties?

objective-c block property
objective-c block syntax cheat sheet
objective-c pass function as parameter
block objective-c
objective-c completion block
objective-c block literal
block copy objective-c
objective-c block weak self

Is it possible to have blocks as properties using the standard property syntax?

Are there any changes for ARC?

@property (nonatomic, copy) void (^simpleBlock)(void);
@property (nonatomic, copy) BOOL (^blockWithParamter)(NSString *input);

If you are going to be repeating the same block in several places use a type def

typedef void(^MyCompletionBlock)(BOOL success, NSError *error);
@property (nonatomic) MyCompletionBlock completion;

Working with Blocks, Describes elements of best practice when writing code with Objective-C using ARC. However, blocks cannot replace everything. For some certain tasks, implementing delegate methods or other kind of programming techniques will remain intact. Nonetheless, it’s clear that we can all use blocks even more in our code from now on, and take advantage of the Objective-C in a greater level.

Here's an example of how you would accomplish such a task:

#import <Foundation/Foundation.h>
typedef int (^IntBlock)();

@interface myobj : NSObject
{
    IntBlock compare;
}

@property(readwrite, copy) IntBlock compare;

@end

@implementation myobj

@synthesize compare;

- (void)dealloc 
{
   // need to release the block since the property was declared copy. (for heap
   // allocated blocks this prevents a potential leak, for compiler-optimized 
   // stack blocks it is a no-op)
   // Note that for ARC, this is unnecessary, as with all properties, the memory management is handled for you.
   [compare release];
   [super dealloc];
}
@end

int main () {
    @autoreleasepool {
        myobj *ob = [[myobj alloc] init];
        ob.compare = ^
        {
            return rand();
        };
        NSLog(@"%i", ob.compare());
        // if not ARC
        [ob release];
    }

    return 0;
}

Now, the only thing that would need to change if you needed to change the type of compare would be the typedef int (^IntBlock)(). If you need to pass two objects to it, change it to this: typedef int (^IntBlock)(id, id), and change your block to:

^ (id obj1, id obj2)
{
    return rand();
};

I hope this helps.

EDIT March 12, 2012:

For ARC, there are no specific changes required, as ARC will manage the blocks for you as long as they are defined as copy. You do not need to set the property to nil in your destructor, either.

For more reading, please check out this document: http://clang.llvm.org/docs/AutomaticReferenceCounting.html

Store an Objective-C block as a property (Example), Blocks in Objective-C are quite useful - if you've lived in JavaScript (or Ruby, If you want to store a reference to one for later use, though, it's not as more awesome way to do it would be just storing it as a property, ala: The nuance is that most of the time, in Objective C you want to use copy instead of retain. When blocks are created, like most variables, they live on the stack. When a copy is performed, the block is copied to the heap. This can be easily done in a property with the copy keyword: @property (nonatomic, copy) SomeBlockType someBlock;

For Swift, just use closures: example.


In Objective-C:

@property (copy)void
@property (copy)void (^doStuff)(void);

It's that simple.

Here is the actual Apple documentation, which states precisely what to use:

Apple doco.

In your .h file:

// Here is a block as a property:
//
// Someone passes you a block. You "hold on to it",
// while you do other stuff. Later, you use the block.
//
// The property 'doStuff' will hold the incoming block.

@property (copy)void (^doStuff)(void);

// Here's a method in your class.
// When someone CALLS this method, they PASS IN a block of code,
// which they want to be performed after the method is finished.

-(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater;

// We will hold on to that block of code in "doStuff".

Here's your .m file:

 -(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater
    {
    // Regarding the incoming block of code, save it for later:
    self.doStuff = pleaseDoMeLater;

    // Now do other processing, which could follow various paths,
    // involve delays, and so on. Then after everything:
    [self _alldone];
    }

-(void)_alldone
    {
    NSLog(@"Processing finished, running the completion block.");
    // Here's how to run the block:
    if ( self.doStuff != nil )
       self.doStuff();
    }
Beware of out-of-date example code.

With modern (2014+) systems, do what is shown here. It is that simple.

How Do I Declare A Block in Objective-C?, How Do I Declare A Block in Objective-C? As a property: @property (​nonatomic, copy, nullability) returnType As a parameter to a C function: This site is not intended to be an exhaustive list of all possible uses of blocks. If you find  An Objective-C class defines an object that combines data with related behavior. Sometimes, it makes sense just to represent a single task or unit of behavior, rather than a collection of methods. 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

For posterity / completeness's sake… Here are two FULL examples of how to implement this ridiculously versatile "way of doing things". @Robert's answer is blissfully concise and correct, but here I want to also show ways to actually "define" the blocks.

@interface       ReusableClass : NSObject
@property (nonatomic,copy) CALayer*(^layerFromArray)(NSArray*);
@end

@implementation  ResusableClass
static  NSString const * privateScope = @"Touch my monkey.";

- (CALayer*(^)(NSArray*)) layerFromArray { 
     return ^CALayer*(NSArray* array){
        CALayer *returnLayer = CALayer.layer
        for (id thing in array) {
            [returnLayer doSomethingCrazy];
            [returnLayer setValue:privateScope
                         forKey:@"anticsAndShenanigans"];
        }
        return list;
    };
}
@end

Silly? Yes. Useful? Hells yeah. Here is a different, "more atomic" way of setting the property.. and a class that is ridiculously useful…

@interface      CALayoutDelegator : NSObject
@property (nonatomic,strong) void(^layoutBlock)(CALayer*);
@end

@implementation CALayoutDelegator
- (id) init { 
   return self = super.init ? 
         [self setLayoutBlock: ^(CALayer*layer){
          for (CALayer* sub in layer.sublayers)
            [sub someDefaultLayoutRoutine];
         }], self : nil;
}
- (void) layoutSublayersOfLayer:(CALayer*)layer {
   self.layoutBlock ? self.layoutBlock(layer) : nil;
}   
@end

This illustrates setting the block property via the accessor (albeit inside init, a debatably dicey practice..) vs the first example's "nonatomic" "getter" mechanism. In either case… the "hardcoded" implementations can always be overwritten, per instance.. a lá..

CALayoutDelegator *littleHelper = CALayoutDelegator.new;
littleHelper.layoutBlock = ^(CALayer*layer){
  [layer.sublayers do:^(id sub){ [sub somethingElseEntirely]; }];
};
someLayer.layoutManager = littleHelper;

Also.. if you want to add a block property in a category... say you want to use a Block instead of some old-school target / action "action"... You can just use associated values to, well.. associate the blocks.

typedef    void(^NSControlActionBlock)(NSControl*); 
@interface       NSControl            (ActionBlocks)
@property (copy) NSControlActionBlock  actionBlock;    @end
@implementation  NSControl            (ActionBlocks)

- (NSControlActionBlock) actionBlock { 
    // use the "getter" method's selector to store/retrieve the block!
    return  objc_getAssociatedObject(self, _cmd); 
} 
- (void) setActionBlock:(NSControlActionBlock)ab {

    objc_setAssociatedObject( // save (copy) the block associatively, as categories can't synthesize Ivars.
    self, @selector(actionBlock),ab ,OBJC_ASSOCIATION_COPY);
    self.target = self;                  // set self as target (where you call the block)
    self.action = @selector(doItYourself); // this is where it's called.
}
- (void) doItYourself {

    if (self.actionBlock && self.target == self) self.actionBlock(self);
}
@end

Now, when you make a button, you don't have to set up some IBAction drama.. Just associate the work to be done at creation...

_button.actionBlock = ^(NSControl*thisButton){ 

     [doc open]; [thisButton setEnabled:NO]; 
};

This pattern can be applied OVER and OVER to Cocoa API's. Use properties to bring the relevant parts of your code closer together, eliminate convoluted delegation paradigms, and leverage the power of objects beyond that of just acting as dumb "containers".

Objective-C Language, Those mutual strong references are called a "retain cycle" and will prevent the release of either object. __weak __typeof(self) weakSelf = self; self.blockProperty​  Just keep in mind that this is only a solution if you are going to use the block in the same function as (or a function called by) the current function. Because the C++ object is on the stack, it will go away, so if whoever you hand the block to copies it and calls it later, the pointer will be invalid.

Of course you could use blocks as properties. But make sure they are declared as @property(copy). For example:

typedef void(^TestBlock)(void);

@interface SecondViewController : UIViewController
@property (nonatomic, copy) TestBlock block;
@end

In MRC, blocks capturing context variables are allocated in stack; they will be released when the stack frame is destroyed. If they are copied, a new block will be allocated in heap, which can be executed later on after the stack frame is poped.

Objective-C blocks example - Fresh Beginning, How to declare and use the Objective-C blocks with syntax and usage. After defining block and declaring it as a property, you can pass it to  Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary. They also have the ability to capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages.

Introduction to Objective-C Blocks, This programming tutorial gives you an introduction of Objective-C blocks writing blocks, you will get used to it like everything else in Objective-C. @​property (nonatomic, strong) NSString *(^blockAsAMemberVar)(void);. Take a look at saveAllInBackground:block: to see if you can make only 1 save and dismiss from that block. You probably won't need to define your own block, just use the block called by Parse SDK. You probably won't need to define your own block, just use the block called by Parse SDK.

Blocks to Basics in Objective-C |, This is crazy convenient, ensuring that any relevant state can be used exactly when it's needed. Most iOS developers now regularly use blocks  Properties are introduced in Objective-C to ensure that the instance variable of the class can be accessed outside the class. The various parts are the property declaration are as follows. Properties begin with @property , which is a keyword

Can I use Objective-C blocks as properties?, objective-c block literal objective-c completion handler. Is it possible to have blocks as properties using the standard property syntax? Are there any changes for  But I see that when using some of Objective-C features that uses Blocks as Arguments in Methods, some variables are assignable, even if they are not declared with this __block statement. Here are 2 codes for example:

Comments
  • Well, because it would be very in handy. I wouldn't need to know what it is as long as I have the syntax right and it behaves like an NSObject.
  • If you don't know what it is, how do you know that it would be very handy?
  • You shouldn't use them If you dont know what they are :)
  • @Moshe here are some reasons that come to mind. Blocks are easier to implement than a full delegate class, blocks are lightweight, and you have access to variables that are in the context of that block. Event Callbacks can be done effectively using blocks (cocos2d uses them almost exclusively).
  • Not completely related, but since some of the comments complain about "ugly" block syntax, here is a great article that derives the syntax from first principles: nilsou.com/blog/2013/08/21/objective-c-blocks-syntax
  • With xCode 4.4 or newer you dont need to synthesize. That will make it even more concise. Apple Doc
  • wow, I didn't know that, thanks! ... Although I often do @synthesize myProp = _myProp
  • @Robert: You are in luck again, because without putting @synthesize the default is what you are doing @synthesize name = _name; stackoverflow.com/a/12119360/1052616
  • @CharlieMonroe - Yes you are probably right, but dont you need a dealloc implementation to nil or release the block property without ARC? (its been a while since I used non-ARC)
  • @imcaptor: Yes, it can cause memory leaks in case you don't release it in dealloc - just like with any other variable.