Blocks in Objective c
Blocks are Objective c`s anonymous functions .
Block is a self-contained, autonomous code fragment, existing always in the scope of another programming structure , e.g. body of a method.
Blocks helps you to :
1) Reduce code
2) Write more cleaner code
3) More reliable code
Block basic syntax :
ReturnType (^Name of the block) (Parameters)
- ReturnType : Any datatype supported by Objective c
- ^Name of the block : Name of the block is always preceded by the carret symbol (^).
- Parameters : Parameters which you want to pass on the block.
Block example :
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int (^myBlock) (int ,int) = ^(int first , int second) { | |
return first / second; | |
}; | |
int result = myBlock(22 ,2 ); | |
NSLog(@"Printing result --- %i",result); | |
// Output is 11 in the console .... |
Blocks used for array enumeration :
Arrays enumeration using blocks is fastest .
>> Use this code for faster enumeration of arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSArray *myArray = @[@"Saurabh",@"Dutta",@"iOS",@"Developer",@"9988207247"]; | |
[myArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { | |
NSLog(@"Object at index %lu is %@",(unsigned long)idx,obj); | |
}]; |
Blocks Advantages:
1) Blocks can do same as methods but methods can`t do all the tasks like blocks
2) Blocks can be parsed to other functions.
3) Blocks are used in multi-threading
4) Blocks have faster array enumeration as compared to for in and for loops .
5) Blocks are simpler to read.
That`s a small introduction to blocks in objective c. More complex part will be covered in the future tutorials .
Thank you :)
The information is very effective and once you can check it out
ReplyDeleteios online training Hyderabad,Bangalore
This article was very helpful ios online training
ReplyDeleteThis article is helpful ios Online course
ReplyDeleteThanks for this beautiful post IOS. It is really good for the beginners and I also liked the post.
ReplyDeleteIOS Training in Bangalore
IOS Training in Marathahalli