协议与类别 [英] Protocol versus Category
问题描述
有人能解释Objective-C中的协议和类别之间的区别吗?您什么时候使用另一个?
Can anyone explain the differences between Protocols and Categories in Objective-C? When do you use one over the other?
推荐答案
协议与Java中的接口是一回事:本质上是一个契约,说,任何实现此协议的类也将实现这些协议.方法."
A protocol is the same thing as an interface in Java: it's essentially a contract that says, "Any class that implements this protocol will also implement these methods."
另一方面,类别仅将方法绑定到类.例如,在 Cocoa 中,我可以为NSObject
创建一个类别,该类别允许我将方法添加到NSObject
类(当然还有所有子类)中,即使我真的没有访问NSObject
的机会.
A category, on the other hand, just binds methods to a class. For example, in Cocoa, I can create a category for NSObject
that will allow me to add methods to the NSObject
class (and, of course, all subclasses), even though I don't really have access to NSObject
.
总结:协议指定了类将实现的方法;类别将方法添加到现有的类中.
To summarize: a protocol specifies what methods a class will implement; a category adds methods to an existing class.
然后,应明确每种方法的正确用法:使用协议声明类必须实现的一组方法,并使用类别将方法添加到现有类中.
The proper use of each, then, should be clear: Use protocols to declare a set of methods that a class must implement, and use categories to add methods to an existing class.
这篇关于协议与类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!