是否遵从某个协议 ios

来源:互联网 发布:360防蹭网软件 编辑:程序博客网 时间:2024/05/21 09:32

respondsToSelector: 和 conformsToProtocol:的区别

conformsToProtocol 是检测一个类是不是遵从某个协议,跟该类是不是实现了该协议的方法没什么关系(当然协议里声明称 required 的方法必须得实现)。

respondsToSelector 是检测一个类或者其父类能不能响应某个消息。以你的例子里,NSObject 是可以响应 mutableCopy 消息的,NSNumber 是 NSObject 的子类,所以 respondsToSelector 返回 true 是没有问题的。respondsToSelector 并不是只检查了方法名,不是有方法声明但是没有实现也可以。它是要求必须要有实现的。 NSObject 类里是有 mutableCopy 方法的实现的,如文档里所说:
Returns the object returned by mutableCopyWithZone:.
This is a convenience method for classes that adopt the NSMutableCopying protocol. An exception is raised if there is no implementation for mutableCopyWithZone:.

所以我们可以猜测一下, NSObject 的 mutableCopy 方法就是去调用 mutableCopyWithZone 并返回结果,如果该类没有实现 mutableCopyWithZone 方法,则抛出异常。


0 0