协议的意义何在? [英] What is the point of Protocols?

查看:16
本文介绍了协议的意义何在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在按照示例代码使用协议编写各种东西,但也使用一些第三方的东西,它们似乎采用了完全不同的方法.有些专门采用接口中的协议使用

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.

推荐答案

协议声明了对象必须响应的一组消息(或者使用 @optional,可以响应).在 Objective-C 中,它唯一的一点(几乎)* 是允许编译器在您传递的对象未使用正确签名实现协议的所有方法时标记警告.

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.

举个简单的例子:NSMutalbeDictionary有一个方法-setObject:ForKey: 设置特定键的值.键被声明为类型 id 这意味着您可以传递任何对象并且编译器不会抱怨.但是,该方法的文档说:

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:

密钥被复制(使用 copyWithZone:;密钥必须符合 NSCopying 协议).

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

所以如果你传递一个没有 -copyWithZone: 方法的对象,你会在运行时得到一个异常,说密钥没有响应 -copyWithZone:.如果编译器能够检测到您的错误,那就太好了.

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<NSCopying>)aKey;

编译器会知道 -copyWithZone: 的要求(它是 NSCopying) 并且会在编译时捕获任何传递不兼容对象的实例.我认为他们没有这样做的原因是为了向后兼容.如果 bbum 正在阅读,他可能知道不阅读的真正原因.

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.

这篇关于协议的意义何在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆