15

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 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

"In the case of UIKit code, you should be fine." Citations needed?
@Manav: You're not wrong -- there's no way to verify (except that it doesn't crash).
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.

3 Comments

Thanks, I know there is a method without animation block. My question is more about block itself. So why nil, not NULL?
nil and NULL are equivalent. By convention, Objective-C typically uses nil where NULL is used in C.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.