I want to use blocks in my application, but I don't really know anything about blocks. Can anyone explain how and why I should use blocks in my code?

- 129,200
- 40
- 280
- 281

- 3,221
- 2
- 34
- 61
-
3They make your life a lot easier! – Mick MacCallum Aug 29 '12 at 11:34
-
2It is like a closure in Javascript. Pieces of code you can pass around. – Thilo Aug 29 '12 at 11:35
-
2They help me from writing a delegate method for every single call back. – Kaan Dedeoglu Aug 29 '12 at 11:35
-
See more about it in Paul Hegarty's iOS Development Course, [Lecture 8 (11:19)](https://www.youtube.com/watch?v=aS6PBmBAP1g&feature=youtu.be&t=11m19s) – danielhadar Feb 23 '17 at 08:12
3 Answers
Blocks are closures (or lambda functions, however you like to call them). Their purpose is that using blocks, the programmer doesn't have to create named functions in the global scope or provide a target-action callback, instead he/she can create an unnamed, local "function" which can access the variables in its enclosing scope and easily perform actions.
For example, when you want to e. g. dispatch an asynchronous operation, such an animation for views, without blocks, and you wanted to be notified of the competion, you had to write:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:context:)];
.... set up animation ....
[UIView commitAnimations];
This is a lot of code, furthermore it implies the presence of a valid self
pointer - that might not always be available (I experience such a thing when I was developing MobileSubstrate-tweaks). So, instead of this, you can use blocks from iOS 4.0 and onwards:
[UIView animateWithDuration:1.0 animations:^{
// set up animation
} completion:^{
// this will be executed on completion
}];
Or, for example, loading online resources with NSURLConnection... B. b. (Before Blocks):
urlConnection.delegate = self;
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)rsp
{
// ...
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// ...
}
// and so on, there are 4 or 5 delegate methods...
A. B. (Anno Blocks):
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rsp, NSData *d, NSError *e) {
// process request here
}];
Much easier, cleaner and shorter.
Quoting a Ray Wenderlich tutorial
Blocks are first-class functions, which is a fancy way of saying that Blocks are regular Objective-C objects. Since they’re objects, they can be passed as parameters, returned from methods and functions, and assigned to variables. Blocks are called closures in other languages such as Python, Ruby and Lisp, because they encapsulate state when they are declared. A block creates a const copy of any local variable that is referenced inside of its scope. Before blocks, whenever you wanted to call some code and have it call you back later, you would typically use delegates or NSNotificationCenter. That worked fine, except it spreads your code all over – you start a task in one spot, and handle the result in another.
For example, in view animation using blocks takes you from having to do all this:
[UIView beginAnimations:@"myAnimation" context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.5];
[myView setFrame:CGRectMake(30, 45, 43, 56)];
[UIView commitAnimations];
To only having to do this:
[UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
[myView setFrame:CGRectMake(54, 66, 88, 33)];
}completion:^(BOOL done){
//
}];

- 129,200
- 40
- 280
- 281
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.