UIViewController dismissViewControllerAnimated completion argument type syntax

14,395

Solution 1

Here's the discussion of blocks from my book:

http://www.apeth.com/iOSBook/ch03.html#_blocks

There's an example there, but here's an example that's closer to the sort of thing you're asking about:

[self transitionFromViewController:fromvc
                  toViewController:tovc
                          duration:0.4
                           options:UIViewAnimationOptionTransitionFlipFromLeft
                        animations:nil
                        completion:^(BOOL done){
                            [tovc didMoveToParentViewController:self];
                            [fromvc removeFromParentViewController];
                        }];

The completion block takes one parameter, a BOOL called "done", but this is not used by its code. The idea is that the animation is performed and then the code in the completion block is run.

It's very important to be comfortable with blocks because they are the way of the future. For example, view animation in iOS 4 uses them, as explained in the "Block Based View Animation" section of my book (read first about the old way, then read about the new iOS 4 way):

http://www.apeth.com/iOSBook/ch17.html#_view_animation

In iOS 5 blocks are even more important; there are more and more situations where they are not optional.

Also blocks are the way to use GCD (grand central dispatch), which is far and away the best way to do multi-threading.

Solution 2

That would be for a completion block. A block is a snippet of code that may be submitted as an argument (often seen, as here, for completion handling) to an API. There are many features of blocks, including the ability to reference memory and maintain state.

See documentation on this increasingly popular feature of Obj-C: http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html

Blocks provide what might be considered callback behavior (typically achieved with delegation or notification), but they allow the programmer to include the logic of the completion behavior in the same context as the initiating action, making the code more expressive and conveying the complete progression of intended behavior concisely.

Share:
14,395
Andy Bowskill
Author by

Andy Bowskill

A software developer and a stroke survivor based in Somerset with a penchant for technology and lemon curd.

Updated on June 12, 2022

Comments

  • Andy Bowskill
    Andy Bowskill about 2 years

    The void (^)(void) syntax of the 'completion' argument type implemented by the UIViewController method:

    - (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^)(void))completion
    

    has piqued my curiosity and I have been unable to find any documentation for it. Please could someone help explain its purpose/meaning?

    Many thanks in advance.