I’ve been writing various stuff using protocols as per example code, but also using some third party stuff, and they seem to adopt quite different approaches. Some specifically adopt the protocols in the interface using
@interface myClass <myProtocol>
others don’t do that at all and merely pass themselves and are then set as delegates, but the end result seems to be exactly the same. I’ve tried both, and they both work fine. If someone was able to explain this I’d be a happy camper! Thanks very much.
A protocol declares a set of messages that an object must respond to (or with
@optional, can respond to). In Objective-C, its only point (almost)* is to allow the compiler to flag up warnings if you pass an object that doesn’t implement all the methods of the protocol with the correct signatures.Taking a simple example: NSMutalbeDictionary has a method -setObject:ForKey: which sets the value for a particular key. The key is declared as type
idwhich means you can pass any object and the compiler will not complain. However, the documentation for the method says:so if you pass an object that doesn’t have a
-copyWithZone:method, you will get a exception at run time saying the key does not respond to-copyWithZone:. It would have been nice if the compiler could have detected your error.If Apple had declared the method
the compiler would have known about the requirement for
-copyWithZone:(it’s the only method declared in NSCopying) and would have caught any instances of passing incompatible objects at compile time. I think the reason they didn’t do that is for backward compatibility. If bbum is reading, he might know the real reason why not.*I say “almost” because you can test to see if an object conforms to a protocol at run time.