The protocol declares a set of messages to which the object should respond (or @optional , may respond to). In Objective-C, its only (almost) * point is to allow the compiler to flag warnings if you pass an object that does not implement all protocol methods with the correct signatures.
Taking a simple example: NSMutalbeDictionary has a method - setObject: ForKey:, which sets a value for a specific key. The key is declared as an id type, which means that you can pass any object, and the compiler will not complain. However, the method documentation states:
The key is copied (using the copyWithZone :; keys must comply with the NSCopying protocol).
therefore, if you pass an object that does not have the -copyWithZone: method, at run time you will get an exception saying that the key does not respond to -copyWithZone: It would be nice if the compiler could detect your error.
If Apple announced a method
-(void)setObject:(id)anObject forKey:(id<NSCopying>)aKey;
the compiler would know about the requirement -copyWithZone: (this is the only method declared by NSCopying ) and catch any instances of passing incompatible objects at compile time. I think the reason they did not do this is backward compatibility. If bbum is reading, he may know the true reason, why not.
* I say "almost" because you can check if the object matches the protocol at startup time.
JeremyP May 04 '11 at 9:50 a.m. 2011-05-04 09:50
source share