objective-c 协议与类别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/360992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Protocol versus Category
提问by Coocoo4Cocoa
Can anyone explain the differences between Protocolsand Categoriesin Objective-C? When do you use one over the other?
谁能解释一下Objective-C 中协议和类别之间的区别?你什么时候用一个?
回答by mipadi
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."
协议与 Java 中的接口是一回事:它本质上是一个契约,上面写着:“任何实现这个协议的类也将实现这些方法。”
A category, on the other hand, just binds methods to a class. For example, in Cocoa, I can create a category for NSObjectthat will allow me to add methods to the NSObjectclass (and, of course, all subclasses), even though I don't really have access to NSObject.
另一方面,类别只是将方法绑定到类。例如,在Cocoa 中,我可以为NSObject它创建一个类别,这将允许我向NSObject类(当然还有所有子类)添加方法,即使我真的没有访问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.
那么,每个人的正确使用应该是清楚的:使用协议声明类必须实现的一组方法,并使用类别向现有类添加方法。
回答by Alex
A protocol says, "here are some methods I'd like youto implement." A category says, "I'm extending the functionality of this class with these additional methods."
一个协议说,“这里有一些我希望你实现的方法。” 一个类别说,“我正在用这些附加方法扩展这个类的功能。”
Now, I suspect your confusion stems from Apple's use of the phrase "informal protocol". Here's the key (and most confusing) point: an informal protocol is actually not a protocol at all. It's actually a category on NSObject. Cocoa uses informal protocols pervasively to provide interfaces for delegates. Since the @protocolsyntax didn't allow optional methods until Objective-C 2.0, Apple implemented optional methods to do nothing (or return a dummy value) and required methods to throw an exception. There was no way to enforce this through the compiler.
现在,我怀疑您的困惑源于 Apple 使用“非正式协议”一词。这是关键(也是最令人困惑)的一点:非正式协议实际上根本不是协议。它实际上是 NSObject 上的一个类别。Cocoa 普遍使用非正式协议为代表提供接口。由于在@protocolObjective-C 2.0 之前语法不允许可选方法,因此 Apple 实现了可选方法不做任何事情(或返回一个虚拟值),并且需要方法来抛出异常。无法通过编译器强制执行此操作。
Now, with Objective-C 2.0, the @protocolsyntax supports the @optionalkeyword, marking some methods in a protocol as optional. Thus, your class conforms to a protocol so long as it implements all the methods marked as @required. The compiler can determine whether your class implements all the required methods, too, which is a huge time saver. The iPhone SDK exclusively uses the Objective-C 2.0 @protocolsyntax, and I can't think of a good reason not to use it in any new development (except for Mac OS X Cocoa apps that need to run on earlier versions of Mac OS X).
现在,在 Objective-C 2.0 中,@protocol语法支持@optional关键字,将协议中的某些方法标记为可选。因此,只要您的类实现了所有标记为 的方法,它就符合协议@required。编译器也可以确定您的类是否实现了所有必需的方法,这可以节省大量时间。iPhone SDK 专门使用 Objective-C 2.0@protocol语法,我想不出有什么好的理由不在任何新的开发中使用它(除了需要在早期版本的 Mac OS X 上运行的 Mac OS X Cocoa 应用程序) .
回答by e.James
Categories:
类别:
A category is a way of adding new methods to all instances of an existing class without modifying the class itself.
类别是一种向现有类的所有实例添加新方法而不修改类本身的方法。
You use a category when you want to add functionality to an existing class without deriving from that class or re-writing the original class.
当您想向现有类添加功能而不从该类派生或重写原始类时,您可以使用类别。
Let's say you are using NSViewobjects in cocoa, and you find yourself wishing that all instances of NSViewwere able to perform some action. Obviously, you can't rewrite the NSViewclass, and even if you derive from it, not all of the NSViewobjects in your program will be of your derived type. The solution is to create a category on NSView, which you then use in your program. As long as you #importthe header file containing your category declaration, it will appear as though everyNSViewobject responds to the methods you defined in the catagory source file.
假设您NSView在 cocoa中使用对象,并且您发现自己希望 的所有实例NSView都能够执行某些操作。显然,您不能重写NSView该类,即使您从它派生,也不是NSView程序中的所有对象都属于您的派生类型。解决方案是在 上创建一个类别NSView,然后在您的程序中使用该类别。只要您#import的头文件包含您的类别声明,它就会显示好像每个NSView对象都响应您在类别源文件中定义的方法。
Protocols:
协议:
A protocol is a collection of methods that any class can choose to implement.
协议是任何类都可以选择实现的方法的集合。
You use a protocol when you want to provide a guarantee that a certain class will respond to a specific set of methods. When a class adopts a protocol, it promises to implement all of the methods declared in the protocol header. This means that any other classes which use that class can be certain that those methods will be implemented, without needing to know anyting else about the class.
当您想保证某个类将响应一组特定的方法时,您可以使用协议。当一个类采用一个协议时,它承诺实现协议头中声明的所有方法。这意味着使用该类的任何其他类都可以确定将实现这些方法,而无需了解有关该类的任何其他信息。
This can be useful when creating a family of similar classes that all need to communicate with a common "controller" class. The communication between the controller class and the controlled classes can all be packaged into a single protocol.
这在创建一系列相似的类时很有用,这些类都需要与一个公共的“控制器”类进行通信。控制器类和受控类之间的通信都可以打包成一个单一的协议。
Side note: the objective-c language does not support multiple inheritance (a class can only derive from one superclass), but much of the same functionality can be provided by protocols because a class can conform to several different protocols.
旁注:objective-c 语言不支持多重继承(一个类只能从一个超类派生),但是协议可以提供许多相同的功能,因为一个类可以符合多个不同的协议。
回答by PEZ
To my understanding Protocols are a bit like Java's Interfaces. Protocols declare methods , but the implementation is up to each class. Categories seems to be something like Ruby's mixins. With Categories you can add methods to existing classes. Even built-in classes.
据我了解,协议有点像 Java 的接口。协议声明方法,但实现取决于每个类。类别似乎类似于 Ruby 的 mixin。使用类别,您可以向现有类添加方法。甚至内置类。
回答by Nam
A protocol allows you to declare a list of methods which are not confined to any particular class or categories. The methods declared in the protocol can be adopted any class/categories. A class or category which adopts a protocol must implements all the required methods declared in the protocol.
协议允许您声明不限于任何特定类或类别的方法列表。协议中声明的方法可以采用任何类/类别。采用协议的类或类别必须实现协议中声明的所有必需方法。
A category allows you to add additional methods to an existing class but they do not allow additional instance variables. The methods the category adds become part of the class type.
类别允许您向现有类添加额外的方法,但它们不允许额外的实例变量。类别添加的方法成为类类型的一部分。
回答by Stalert John
Definitions from S.G.Kochan's "Programming in Objective-C":
SGKochan 的“Objective-C 编程”中的定义:
Categories:
类别:
A category provides an easy way for you to modularize the definition of a class into groups or categories of related methods. It also gives you an easy way to extend an existing class definition without even having access to the original source code for the class and without having to create a subclass.
类别为您提供了一种将类的定义模块化为相关方法的组或类别的简单方法。它还为您提供了一种扩展现有类定义的简单方法,甚至无需访问该类的原始源代码,也无需创建子类。
Protocols:
协议:
A protocol is a list of methods that is shared among classes. The methods listed in the protocol do not have corresponding implementations; they're meant to be implemented by someone else (like you!). A protocol provides a way to define a set of methods that are somehow related with a specified name. The methods are typically documented so that you know how they are to perform and so that you can implement them in your own class definitions, if desired. A protocol list a set of methods, some of which you can optionally implement, and others that you are required to implement. If you decide to implement all of the required methods for a particular protocol, you are said to conform to or adopt that protocol. You are allowed to define a protocol where all methods are optional, or one where all are required.
协议是在类之间共享的方法列表。协议中列出的方法没有对应的实现;它们旨在由其他人(如您!)实施。协议提供了一种定义一组方法的方法,这些方法以某种方式与指定的名称相关。这些方法通常被记录下来,以便您知道它们将如何执行,并且如果需要,您可以在自己的类定义中实现它们。协议列出了一组方法,其中一些您可以选择实现,而另一些则需要您实现。如果您决定为特定协议实现所有必需的方法,则表示您符合或采用该协议。您可以定义一个协议,其中所有方法都是可选的,或者所有方法都是必需的。
回答by dreamlax
Protocols are contracts to implement the specified methods. Any object that conforms to a protocol agrees to provide implementations for those methods. A good use of a protocol would be to define a set of callback methods for a delegate (where the delegate must respond to all methods).
协议是实现指定方法的契约。任何符合协议的对象都同意为这些方法提供实现。协议的一个很好的用途是为委托定义一组回调方法(委托必须响应所有方法)。
Categories provide the ability to extend a current object by adding methods to it (class or instance methods). A good use for a category would be extending the NSString class to add functionality that wasn't there before, such as adding a method to create a new string that converts the receiver into 1337 5P34K.
类别提供了通过向当前对象添加方法(类或实例方法)来扩展当前对象的能力。一个类别的一个很好的用途是扩展 NSString 类以添加以前不存在的功能,例如添加一个方法来创建一个将接收器转换为 1337 5P34K 的新字符串。
NSString *test = @"Leet speak";
NSString *leet = [test stringByConvertingToLeet];

