How to use blocks in iOS?

 In iOS, blocks are an Apple extension to the C objective language motivated by the desire to pass a small amount of code in API calls to the Grand Central Dispatch multithreading system. They also have the ability to record values from the

surrounding scope, making them similar to closures or lambdas within other rogramming languages. Moreover, blocks are being available in iOS since version 4.


The most fundamental form of a block is a "block literal". This includes a caret character ("^"). It is followed by a set of curly braces having the actual code. Blocks appear inline along with the rest of the user code within a method or function.The use of blocks in iOS often involves a code inclusion in “block literal” form as parameters for methods. Besides, these are part of the iOS API.


The language extension that builds blocks also includes a capability known as a closure. This makes the usage of the blocks much easier and more practical. This capability is also found in programming languages like Lisp, Python, and Ruby. It records those variables and their values that the code in the block refers to and that is in the same lexical scope. Moreover, these values are available when the code is executed at some time later.


With the inclusion of blocks, many of the other iOS APIs also have initiated methods that take blocks as parameters. These may be found in the methods for NSOperationQueue, similar to Grand Central Dispatch, which places the block in a queue.more info visit:ios app development course
With iOS 4 and the latest versions, numerous methods and functions of the system frameworks are starting to take blocks as parameters. These include the following:
 Completion handlers
 Notification handlers
 Error handlers

 Enumeration
 View animation and transitions
 Sorting
Block Syntax
The fundamental syntax to define a” block literal” in iOS uses the caret symbol (^),
such as:
^{
NSLog(@"This is a block");
}
Under the function and method definitions, the brackets indicate the beginning and end of the block. An example explains, the block doesn’t return any value, and doesn’t take any arguments.
In the same way that users can use a function pointer to refer to a C function. Moreover, he can also declare a variable to keep track of a block, such as:
void (^simpleBlock)(void);
If anyone is not used to deal with C function pointers, the syntax may look a little unusual. This example reveals a variable called simpleBlock to refer to a block that doesn’t take arguments and returns a value. This means the variable can be assigned the literal block given above, like the following:
simpleBlock = ^{
NSLog(@"This is a block");
};
This is just like another variable task. Hence, the statement must be aborted by a semi-colon after the closing brace. Moreover, user can also merge the variable declaration and task:
void (^simpleBlock)(void) = ^{
NSLog(@"This is a block");
};
Once the user has declared and allotted a block variable, he can use it to induce the block, like:
simpleblock();


Blocks in iOS example
Here, for example, the user gets to use a block-based method for car animation. But the iOS block objects also include numerous other uses, especially in Grand Central Dispatch and the NSOperationQueue class. These are the two suggested technologies for processing coincidently.


One of the values of using blocks is that the user has the option to access local variables (similar instance variables). This he can’t do in a function or a callback.


Moreover, the user also doesn’t have to pass data around. Since a block can change variables to pass data backward. In addition to this, in iOS, if the user needs to modify anything, there’s no API to modify, with its associated wave


effect. Sometimes it becomes easier to follow what’s happening by stating a block
variable and passing the same as the argument to the method. The statement syntax, nonetheless, is equal to the basic syntax for function pointers. This is except that the user uses a Caret (^) as a substitute for an asterisk pointer (*).


In case the user looks at animateWithDuration:animations:completion: in the UIView class reference, he will see-
+ (void)animateWithDuration:(NSTimeInterval)duration

animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion;


Apple org. is now considering blocks as a primary design pattern, up there with legacy and delegation. Hence, we don’t to be surprised to find blocks being used much more.
However, because it’s somewhat advanced, the code is explored in depth. Thus, the user will be comfortable with blocks, despite the really uncanny syntax.

To begin, the below is the syntax that defines animations as a block that doesn’t have parameters and return value:


void (^)(void))animations
The “completion” is stated as a block that doesn’t have a return value and takes a single Boolean argument variable:


(void (^)(BOOL finished))completion
When the user develops a block inline, he just uses the caret (^) operator to mention the starting of a block. Later follows with the code included within the normal braces. The following will going on with


animations:^ {
self.car.center = center;
}
and
completion:^(BOOL finished){
[self rotate];
}
However, in the following example, the user uses blocks inline. He could also state them like any other local parameter. Now, the user has the option to add the code in bold to his testDrive method replacing what he already has in that
location.
- (IBAction)testDrive:(id)sender {
CGPoint center = CGPointMake(car.center.x,
self.view.frame.origin.y + car.frame.size.height/2);
void (^animation)()= ^() {
self.car.center = center;
};
void (^completion)(BOOL) = ^(BOOL finished){
[self rotate];
};
[UIView animateWithDuration:3 animations:animation
completion:completion];
}

The statement in Listing 10-2 is very much the same as the user follows in the earlier method statement. The exception is that the identifiers have been transferred around a little. Both are bolded to make it a little easier to check the following;


+ (void)animateWithDuration:(NSTimeInterval)duration
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion;


Hereunder, the user is stating two different block variables by using the ^ operator. The first one with the name of an animation that doesn’t have a return value, and the second one with the name of completion that doesn’t have a return value and accepts BOOL as an only argument:


void (^animation)()
void (^completion)(BOOL)


This is like any other variable statement (int i = 1, for example), where the user follows a similar sign with its definition.
The user uses the ^ operator again to mention the block literal starting — the definition allotted to the block variable. In the iOS, The block literal comprises argument names (finished) as well as the body (code) of the block. And the same is aborted using a semicolon:


void (^animation)() = ^() {
self.car.center = center;
};
void (^completion)(BOOL) = ^(BOOL finished){
[self rotate];
};
After this the user will get the hang of blocks, he’ll find all sorts of ways to use them to simplify the code easily.
Summing Up
Today, in iOS, blocks have become popular with programmers, and Apple also suggests their use. Why blocks are so popular? Blocks put important pieces of code in eminent places where they are easily found, making code more readable and easier to change.


In iOS, Blocks are specifically useful in callbacks, where the code for a handout with a response to an action may be included as a variable in the method starting the action. Moreover, these include a different type & style of programming. It takes some time to use its unfamiliar syntax, but it can be very useful and convenient. Get more insights from ios online training.

Comments

Popular posts from this blog

iOS - Objective C Basics

14 must knows for an iOS developer

iOS UI Segmented Controls