我看到了通过以下方式定义的目标-c协议:
@protocol MyProtocol <SomeOtherProtocol>
// ...
@end为什么协议采用其他协议?我特别好奇为什么协议会采用NSObject协议。
发布于 2011-09-22 20:29:06
它与类的继承是一个简单的概念。如果一个协议采用另一个协议,它就“继承”了该协议所声明的方法。
NSObject协议特别声明了诸如respondsToSelector:之类的方法。因此,如果您声明一个具有@protocol方法的@optional,这尤其有用,因为当您随后将对符合此协议的对象调用方法时,您需要在调用该方法之前检查该对象是否响应该方法,如果此方法是可选的。
@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 声明为实现 respondsToSelector的类型(否则会有一些警告)时,才能在myDelegate上调用。这就是为什么<SomeProtocol>协议需要采用自己的<NSObject>协议,而<NSObject>协议本身就声明了这个方法。
您可能会认为SomeProtocol是“任何对象,无论其类型(id),它只需实现在SomeProtocol中声明的方法,包括在父协议NSObject中声明的方法。因此,它可以是任何类型的对象,但可以是,因为 id<SomeProtocol> 采用了 NSObject 协议本身,因此保证允许在该对象上调用E 238 respondsToSelector E 142id<SomeProtocol>>,允许您在调用该对象之前检查该对象是否实现了给定的方法,如果它是可选的E 243/code>。
请注意,您也可能不让SomeProtocol采用NSObject协议,而是将变量声明为id<SomeProtocol,NSObject> myDelegate,以便仍然可以调用respondsToSelector:__。但是如果你这样做的话,你需要用这种方式声明你所有的变量--无论你使用这个协议.因此,让SomeProtocol直接采用NSObject协议更符合逻辑;)
发布于 2011-09-22 20:28:38
继承.
https://stackoverflow.com/questions/7521001
复制相似问题