2010-02-02 7 views

Odpowiedz

33

Będziesz chciał zaimplementować NSCoding protocol. Zaimplementuj initWithCoder: i encodeWithCoder: a twoja niestandardowa klasa będzie działać z NSKeyedArchiver i NSKeyedUnarchiver.

Twój initWithCoder: powinien wyglądać następująco:

- (id)initWithCoder:(NSCoder *)aDecoder 
{ 
    if(self = [super init]) // this needs to be [super initWithCoder:aDecoder] if the superclass implements NSCoding 
    { 
     aString = [[aDecoder decodeObjectForKey:@"aString"] retain]; 
     anotherString = [[aDecoder decodeObjectForKey:@"anotherString"] retain]; 
    } 
    return self; 
} 

i encodeWithCoder:

- (void)encodeWithCoder:(NSCoder *)encoder 
{ 
    // add [super encodeWithCoder:encoder] if the superclass implements NSCoding 
    [encoder encodeObject:aString forKey:@"aString"]; 
    [encoder encodeObject:anotherString forKey:@"anotherString"]; 
} 
+1

+1 może trzeba zadzwonić '[SUPER initWithCoder: aDecoder]' lub '[Super encodeWithCoder: enkodera ] 'w zależności od klasy, którą tworzysz podklasy. =) –

+0

Doh! Ładne znalezisko - naprawione. –

+0

Mam pytanie dotyczące sprawdzonych metod ... Czy powinienem sprawić, by klasa mogła być seryjna, czy mogę zostawić to programistce interfejsu użytkownika, aby przekształcić ją do postaci szeregowej w dowolnym pożądanym wyjściu? – Patricia

Powiązane problemy