议定书的要点是什么? [英] What is the point of Protocols?

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

问题描述

我一直在使用协议来编写各种各样的东西,例如代码,还使用了一些第三方的东西,而且他们似乎采用了不同的方法。一些具体采用接口中的协议使用

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协议) / p>

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.

如果Apple已经声明了方法

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天全站免登陆