no known instance method for selector 'copy' on protocol conforming to NSCopying and NSObject

StackOverflow https://stackoverflow.com/questions/21199174

  •  29-09-2022
  •  | 
  •  

Pergunta

When I compile the code below the line id copiedData = [_localData copy]; results in the compiler error "no known instance method for selector 'copy'." Given that _localData is of type id<IGTestClassData> and given that IGTestClassData conforms to both NSCopying and NSObject why does it not have a copy method?

IGTestClass.h file

#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 file

#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
Foi útil?

Solução

Neither protocol NSCopying nor protocol NSObject declares -copy.

NSCopying declares -copyWithZone: only. One solution would be to call [_localData copyWithZone:nil].

Class NSObject declares -copy even though protocol NSObject does not. One solution would be to declare your ivar as type NSObject<IGTestClassData> *.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top