What is the point of Protocols?

后端 未结 3 571
傲寒
傲寒 2020-12-19 23:05

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 specific

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-19 23:56

    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 id which means you can pass any object and the compiler will not complain. However, the documentation for the method says:

    The key is copied (using copyWithZone:; keys must conform to the NSCopying protocol).

    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

    -(void)setObject:(id)anObject forKey:(id)aKey;
    

    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.

提交回复
热议问题