Objective-C delegate coding practices
I have some coding practices involving delegates that I'm not sure of. First of all, if a delegate protocol has no optional methods (all required), is it a recommended practice to use respondsToSelector:
to check whether the delegate object implements that method? And second,开发者_JAVA百科 do I need to check whether the delegate isn't nil
before calling a method on it? In my brief experiments, calling a method on a nil
object doesn't do anything, but what is the recommended practice here?
Thanks
First of all, if a delegate protocol has no optional methods (all required), is it a recommended practice to use respondsToSelector: to check whether the delegate object implements that method?
If it's required then you should not check for it. It is required right? For optional methods, you should definitely check.
And second, do I need to check whether the delegate isn't nil before calling a method on it? In my brief experiments, calling a method on a nil object doesn't do anything, but what is the recommended practice here?
Yes, your observations are correct. Sending messages to nil is harmless. As for best practices, if the delegate is nil, the caller of your code is not interested in whatever delegate methods you're providing, so no need to do any extra checks there.
精彩评论