What is the purpose of using blocks

倾然丶 夕夏残阳落幕 提交于 2020-01-09 12:38:07

问题


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?


回答1:


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.




回答2:


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){
    //
}];



回答3:


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.



来源:https://stackoverflow.com/questions/12176961/what-is-the-purpose-of-using-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!