问题描述
我对Objective-C协议和类别的一些概念感到困惑。
I am little confused about some concepts around Objective-C protocols and categories.
协议和类别可以由Objective-C中的子类继承吗?
Can protocols and categories be inherited by subclasses in Objective-C?
推荐答案
类别是在运行时添加到类的方法的集合。因为Objective-C使用动态绑定,这意味着类中定义的方法可用于类及其所有子类。特别是选择器在调用它们时绑定到方法,而不是在编译期间或程序首次加载时。加载类别时,类别会添加到类中。
Categories are collections of methods that are added to a class at run time. Because Objective-C uses dynamic binding, this means that the methods defined in a category are available to the class and all of its subclasses. Specifically selectors are bound to methods at the point where they are invoked, not during compilation or when the program first loads. Categories are added to classes when they (the categories) are loaded.
协议定义符合它们的类承诺实现的方法签名集合。一旦类声明它符合协议,就好像方法在该类的接口中声明并且继承规则完全相同:子类继承协议方法的声明和实现,但也可以选择覆盖超类实现。
Protocols define collections of method signatures that the classes conforming to them promise to implement. Once a class has declared that it conforms to a protocol its as if the methods are declared in that class's interface and the rules of inheritance are exactly the same: subclasses inherit the declaration and implementation of the protocol methods but may also choose to override the superclass implementation.
可以扩展协议本身以生成新协议。由原始协议中方法的超集组成。实际上,正如大多数类继承自 NSObject
类一样,大多数协议都扩展了 NSObject
协议(协议名称和类)名称在不同的名称空间中)。这样,声明为 id< WhateverProtocol>
的对象可以发送基本消息,如 -retain
, -release
等,不会产生编译器警告。
Protocols themselves can be extended to produce new protocols. consisting of a superset of the methods in the original protocol. In fact, just as most classes inherit from the NSObject
class, most protocols extend the NSObject
protocol (protocol names and class names are in different name spaces). This is so that objects declared as id<WhateverProtocol>
can be sent basic messages like -retain
, -release
and so on without generating compiler warnings.
这篇关于Objective-C协议和类别可以继承吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!