加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Objective-C:将一个实现协议的类别添加到现有类中,是否使对象符

发布时间:2020-12-16 07:08:42 所属栏目:百科 来源:网络整理
导读:Objective-C:将一个实现协议的Category添加到现有Class中,是否使从该类实例化的所有Object都符合该协议? 进一步来说: [myObject conformsToProtocol:@protocol(ProtocolThatWasImplementedViaACategory)]; 返回TRUE? 解决方法 是的,确实如此 – 假设您在
Objective-C:将一个实现协议的Category添加到现有Class中,是否使从该类实例化的所有Object都符合该协议?

进一步来说:

[myObject conformsToProtocol:@protocol(ProtocolThatWasImplementedViaACategory)];

返回TRUE?

解决方法

是的,确实如此 – 假设您在类别的@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

输出是:

conforms to Dummy? 1

您可以阅读有关conformsToProtocol:如何在documentation中工作的说明:

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读