Objective-C:将一个实现协议的类别添加到现有类中,是否使从该类实例化的所有对象都符合该协议?
更具体地说:
[myObject conformsToProtocol:@protocol(ProtocolThatWasImplementedViaACategory)];
返回TRUE
?
答案 0 :(得分:1)
是的,确实如此 - 假设您在类别的@interface声明中添加了适当的声明。你可以自己检查一下:
@interface MyClass : NSObject
@end
@protocol Dummy <NSObject>
-(void)dummyMethod;
@end
@interface MyClass (MyCategory) <Dummy>
@end
@implementation MyClass (MyCategory)
+ (void)load {
BOOL conforms = [self conformsToProtocol:@protocol(Dummy)];
NSLog(@"conforms to Dummy? %@", @(conforms));
}
@end
输出结果为:
符合Dummy? 1
您可以在documentation:
中阅读conformsToProtocol:
的工作原理说明
A class is said to “conform to” a protocol if it adopts the protocol or inherits from another class that adopts it. Protocols are adopted by listing them within angle brackets after the interface declaration. For example, here MyClass adopts the (fictitious) AffiliationRequests and Normalization protocols:
@interface MyClass : NSObject <AffiliationRequests, Normalization>