Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Block Syntax

Obj-C blocks are something I'm just using for the first time recently. I'm trying to understand the following block syntax:

In the header file:

@property (nonatomic, copy) void (^completionBlock)(id obj, NSError *err);

In the main file:

-(void)something{

id rootObject = nil;

// do something so rootObject is hopefully not nil

    if([self completionBlock])
        [self completionBlock](rootObject, nil); // What is this syntax referred to as?
}

I appreciate the assistance!

like image 587
JaredH Avatar asked Sep 21 '12 07:09

JaredH


2 Answers

Blocks are Objects.

In your case inside the method you are checking if the block is not nil and then you are calling it passing the two required arguments ...

Keep in mind that blocks are called in the same way a c function is ...

Below i have split the statement in two to let you understand better :

[self completionBlock]  //The property getter is called to retrieve the block object
   (rootObject, nil);   //The two required arguments are passed to the block object calling it
like image 76
aleroot Avatar answered Oct 12 '22 22:10

aleroot


Its a block property, you can set a block at runtime.

Here is the syntax to set

As it is void type, so within the class you can set a method by following code

self.completionBlock = ^(id aID, NSError *err){
    //do something here using id aID and NSError err
};

With following code you can call the method/block set previously.

if([self completionBlock])//only a check to see if you have set it or not
{
        [self completionBlock](aID, nil);//calling
}
like image 35
A Amjad Avatar answered Oct 12 '22 23:10

A Amjad