2013-06-06 3 views
-3

내가 객체 (사용자 정의 개체)의 배열을 가지고 배열, 그것은 "좋아"라고 내가 NSUserDefault에서이 배열을 저장하려고 할 때이 오류IOS : NSUSerdefault에 저장 객체

내 코드가 있습니다

에게 좋아하는 내부

- 클래스 MyObject를에서> (오브젝트 1, object2, 오브젝트 4 ...)

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
    NSData* myClassArrayData = [NSKeyedArchiver archivedDataWithRootObject:favorite]; 
    [defaults setObject:myClassArrayData forKey:@"favorite"]; 

내 오류 :

[MyObject encodeWithCoder:]: unrecognized selector sent to instance 
,

왜?

+1

http://stackoverflow.com/questions/4317164/save-own-class-with-nscoder http://stackoverflow.com/questions/1659922/ conversion-a-nsobject-into-nsdata – Mar0ux

답변

4

사용자 정의 개체 인 MyObject을 케이스에 저장하려면 클래스에 NSCoder 인터페이스를 구현해야합니다.

인터페이스는 두 가지 방법을 갖는다 :

- (id) initWithCoder:(NSCoder *)aDecoder { 
    self = [super init]; 

    if (self) { 

     self.identifier = [aDecoder decodeIntegerForKey:@"identifier"]; 
     self.name = [aDecoder decodeObjectForKey:@"name"]; 
     /* continue with all the properties that need to be restored */ 

    } 

    return self; 
} 

- (void) encodeWithCoder:(NSCoder *)aCoder { 
    [aCoder encodeInteger:self.identifier forKey:@"identifier"]; 
    [aCoder encodeObject:self.name forKey:@"name"]; 
    /* continue with all the properties that need to be saved */ 
} 
+0

그게 컴파일 문제입니다. 런타임시 인스턴스를 인식 할 수없는 selector를 보내지 않을 것입니다. –

+2

오류에서'MyObject'는 클래스를 만들기 위해 구현해야하는 두 가지 메소드 중 하나 인'encodeWithCoder :'를 인식하지 못한다고 명시되어 있습니다. 'NSCoder' 인터페이스. – rckoenes

+0

예, 메소드를 제공해야합니다. 개체가 프로토콜을 준수하는지 지정하는지 여부는 컴파일시에만 중요합니다. –

관련 문제