Is it okay to pass in NULL to a block parameter?

后端 未结 2 1242
难免孤独
难免孤独 2021-01-17 11:41

iOS does not scream at me when I pass in NULL or nil to the completion block in animateWithDuration:animations:completion: but does th

相关标签:
2条回答
  • 2021-01-17 12:00

    This is okay as long as you can trust that the code to which you are passing the nil won't try to call it as a block.

    A quick demonstration:

    typedef void (^GenericBlock)(void);
    
    void useThisBlock(GenericBlock block){
        block();
    }
    
    useThisBlock(^{NSLog(@"All okay.");});
    useThisBlock(nil);    // Compiles but crashes
    

    The inner code must check the block first: if( block ) block();

    In the case of UIKit code, you should be fine.

    0 讨论(0)
  • 2021-01-17 12:01

    Passing nil is fine, and in my opinion yields cleaner-reading code.

    If you don't want to use a completion block, for this case you can also use the [UIView animateWithDuration:animations:] method.

    0 讨论(0)
提交回复
热议问题