objective-c - 为什么 Objective-c 协议(protocol)采用其他协议(protocol)?

标签 objective-c ios protocols nsobject

我见过以下列方式定义的 Objective-c 协议(protocol):

@protocol MyProtocol <SomeOtherProtocol>
// ...
@end

为什么协议(protocol)采用其他协议(protocol)?我特别好奇为什么一个协议(protocol)会采用NSObject协议(protocol)。

最佳答案

它与类的继承是同一个概念。 如果一个协议(protocol)采用了另一个协议(protocol),它“继承”了这个采用的协议(protocol)声明的方法。

NSObject协议(protocol)特别声明了方法,例如 respondsToSelector: .因此,如果您声明 @protocol,这将特别有用。有 @optional方法,因为当您随后在符合此协议(protocol)的对象上调用方法时,如果此方法是可选的,则需要在调用之前检查对象是否响应该方法。


@protocol SomeProtocol <NSObject>
-(void)requiredMethod;
@optional
-(void)optionalMethod;
@end

@interface SomeObject : NSObject
-(void)testMyDelegate;
@property(nonatomic, assign) id<SomeProtocol> myDelegate;
@end

@implementation SomeObject
@synthesize myDelegate

-(void)testMyDelegate {
    // Here you can call requiredMethod without any checking because it is a required (non-optional) method
    [self.myDelegate requiredMethod];

    // But as "optionalMethod" is @optional, you have to check if myDelegate implements this method before calling it!
    if ([myDelegate respondsToSelector:@selector(optionalMethod)]) {
        // And only call it if it is implemented by the receiver
        [myDelegate optionalMethod];
    }
}
@end

您只能调用respondsToSelector在 myDelegate 上,如果 myDelegate被声明为实现 respondsToSelector 的类型 (否则你会有一些警告)。这就是为什么 <SomeProtocol>协议(protocol)需要自己采用 <NSObject>协议(protocol),它本身声明了这个方法。

你可能会想到id<SomeProtocol>作为“任何对象,无论其类型 (id),它只需要实现在 SomeProtocol 中声明的方法,包括在父协议(protocol) NSObject 中声明的方法。因此它可以是任何类型的对象,但 < strong>因为 SomeProtocol 本身采用了 NSObject 协议(protocol),所以保证你可以在这个对象上调用 respondsToSelector,允许你在调用它之前检查对象是否实现了给定的方法,如果它是可选的.


请注意,您也可以不生成 SomeProtocol采用NSObject协议(protocol),而是将您的变量声明为 id<SomeProtocol,NSObject> myDelegate这样你仍然可以调用respondsToSelector: .但是如果你这样做,你将需要在你使用这个协议(protocol)的任何地方以这种方式声明你的所有变量......所以这更符合逻辑 SomeProtocol直接采纳NSObject协议(protocol);)

关于objective-c - 为什么 Objective-c 协议(protocol)采用其他协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7521001/

相关文章:

ios - 在不影响其他 UITableViewCell 的情况下为 UITableViewCell 设置动画按钮

c++ - 在 .mm 文件中无法识别预编译 header 中的#define

ios - CAEmitterLayer 未显示

c - 编写网络协议(protocol)

swift - CollectionView 委托(delegate)错误

java - 如何检查新的 JSON 文件是否可用?

ios - 如何暂停游戏一段时间然后重新开始

ios - 是否有内置的方法可以在iOS 6 UITextField中从右向左输入文本?

iphone - 是否有可能对同一个 NSString 使用多个 NSCharacterSet 对象?

objective-c - Swift 类不符合带有错误处理的 Objective-C 协议(protocol)