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 ^{ }
?
Asked
Active
Viewed 7,977 times
15

pixelfreak
- 17,714
- 12
- 90
- 109
2 Answers
38
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.

jscs
- 63,694
- 13
- 151
- 195
-
2"*In the case of UIKit code, you should be fine.*" Citations needed? – Manav Sep 17 '12 at 06:53
-
@Manav: You're not wrong -- there's no way to verify (except that it doesn't crash). – jscs Sep 17 '12 at 06:59
6
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.

sho
- 759
- 5
- 16
-
Thanks, I know there is a method without animation block. My question is more about block itself. So why `nil`, not `NULL`? – pixelfreak Dec 20 '11 at 00:20
-
`nil` and `NULL` are equivalent. By convention, Objective-C typically uses `nil` where `NULL` is used in C. – sho Dec 20 '11 at 00:25
-
11that'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](http://stackoverflow.com/questions/557582/null-vs-nil-in-objective-c) question for further information. – Gabriele Petronella Dec 06 '12 at 23:58