Block Objects
Block Objects are first-class Objects in Objective C programming language.We can build the code dynamically by passing a block object to a method as a parameter and return the block object from a method.
Constructing block objects is similar to constructing traditional C functions.Block objects can have return value and can accept the parameters.Block objects can be defined inline as well as a block of code, similar to a C function.
Block objects are new to iOS and Mac developers and syntax of block object is tricky.In order to understand the syntax of block object,we need to understand the basic difference between the syntax of block objects and C functions.
For example we have a method in Objective C that accepts two integer vaules of type NSInteger and returns the addition of these two values.
-(NSInteger) addition:(NSInteger)paramVaue1 :(NSInteger)paramValue2{
return paramValue1 + paramValue2;
}
Now we will translate the above code into pure C function as below.
NSInteger addition(NSInteger paramVaue1 , NSInteger paramValue2){
return paramValue1 + paramValue2;
}
Now we can observe the difference between pure C syntax and Object C syntax.Now we write the above code as a block object:
NSInteger (^addition)(NSInteger,NSInteger)=
^(NSInteger paramVaue1 , NSInteger paramValue2){
return paramValue1 + paramValue2;
};
Variables in Block Objects
Now we need to understand the use of variables in Block objects.
- Local variables in block objects work same as in Objective C methods.For inline block objects the variables are local variables which are defined within the block object and defined within the method in which block object is created.
- We can't use "self" in independent block object in Objective c class.If we have to access "self" in block object,we must pass that object to the block object as a parameter.
- We can refer to "self" in inline block object only if "self" is present in the lexical scope inside which the block object is created.
- The block object has read-write access to variables defined inside the block object's body.
- We can access the declared properties of the NSObject inside independent block objects only if we use the setter and getter methods of these properties.So we can't access the declared properties of an object using dot notation inside an independent block object.
Use of Block Objects
Block objects are packages of code that usually appear in the form of methods in Objective C. Block objects, together with GCD creates a environment in which we can deliver high performance multithreaded iOS and Mac applications.
If detailed info required or other help required related to Block Objects please send mail to pkumar5616@gmail.com