What is the purpose of using blocks

前端 未结 3 605
孤独总比滥情好
孤独总比滥情好 2020-12-13 05:00

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?

3条回答
  •  忘掉有多难
    2020-12-13 05:09

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

提交回复
热议问题