当我编译行id copiedData = [_localData copy];
下面的代码时,会导致编译器错误“没有已知的选择器'copy'实例方法。”鉴于_localData
类型为id<IGTestClassData>
并且IGTestClassData
符合NSCopying
和NSObject
,为什么它没有copy
方法?
IGTestClass.h文件
#import <Foundation/Foundation.h>
@protocol IGTestClassData<NSCopying, NSObject>
@property (nonatomic) NSString* localId;
@end
@interface IGTestClass : NSObject
{
@protected
id<IGTestClassData> _localData;
}
-(void)doTest;
@end
IGTestClass.m文件
#import "IGTestClass.h"
@implementation IGTestClass
-(instancetype)initWithLocalData:(id<IGTestClassData>)localData
{
self = [super init];
if (self)
{
_localData = localData;
}
return self;
}
-(void)doTest
{
id copiedData = [_localData copy];
}
@end
答案 0 :(得分:5)
协议NSCopying
和协议NSObject
均未声明-copy
。
NSCopying
仅声明-copyWithZone:
。一种解决方案是致电[_localData copyWithZone:nil]
。
类NSObject
声明-copy
,即使协议NSObject
没有。一种解决方案是将您的ivar声明为NSObject<IGTestClassData> *
类型。