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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…