iOS does not scream at me when I pass in NULL or nil to the completion block in animateWithDuration:animations:completion: but does that mean it's okay? Or is it better to open an empty ^{ }?
2 Answers
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.
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.
3 Comments
pixelfreak
Thanks, I know there is a method without animation block. My question is more about block itself. So why
nil, not NULL?sho
nil and NULL are equivalent. By convention, Objective-C typically uses nil where NULL is used in C.Gabriele Petronella
that's not exactly true in ARC.
nil means object and must be used where id is expected, whereas NULL means a non-object non valid pointer and must be used where (void *) is expected. Take a look at this question for further information.