I’ve implemented a custom delegate, RandomClassDelegate, in RandomClass.m and RandomClass.h. Now I need to implement the delegate variable, and have it make calls to the methods in the protocol as follows:
[self.delegate randomClassDelegateMethod];
Obviously, if the delegate was never set, this is going to crash the program and cause a run time error. Obvious solution is to just do:
if (delegate)
{
[self.delegate randomClassDelegateMethod];
}
But I’m wondering if this is the correct pattern or if there is a better way to do this, maybe in the protocol or somewhere else?
You should use
-respondsToSelector:to check if the delegate is valid:Don’t worry about checking for
nil, as you can send a message to a nil object and it will do nothing.