在符合NSCopying和NSObject的协议上没有已知的选择器'copy'实例方法

时间:2014-01-18 02:08:30

标签: objective-c nsobject nscopying

当我编译行id copiedData = [_localData copy];下面的代码时,会导致编译器错误“没有已知的选择器'copy'实例方法。”鉴于_localData类型为id<IGTestClassData>并且IGTestClassData符合NSCopyingNSObject,为什么它没有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

1 个答案:

答案 0 :(得分:5)

协议NSCopying和协议NSObject均未声明-copy

NSCopying仅声明-copyWithZone:。一种解决方案是致电[_localData copyWithZone:nil]

NSObject声明-copy,即使协议NSObject没有。一种解决方案是将您的ivar声明为NSObject<IGTestClassData> *类型。