Objective-C: Why check nil before respondsToSelector:?

Viewed 4600

I've seen code like:

if (delegate != nil && [delegate respondsToSelector:@selector(doSomething)]) ...

But, sending a message to nil just returns nil (which evaluates to NO), so why not just do:

if ([delegate respondsToSelector:@selector(doSomething)]) ...

Is the former faster if delegate == nil? Either way, I prefer the latter cause it's less code.

And, less is better than more. Every Unix pro knows that.

3 Answers

There's a syntactical issue here- if you're sending -respondsToSelector to a nil object, it will always return nil. This is why you would do such a thing.

Related