2011-05-15 15 views
0

所以我有一個使用舊式encodeObject:/ decodeObject NSCoder序列化的項目。我需要爲序列化過程添加一個新對象,但之前保存的文檔會因爲decodeObject嘗試解碼那些不存在的東西而崩潰。需要使用NSCoder encodeObject添加附加對象:/ decodeObject

-(void) encodeWithCoder:(NSCoder *)aCoder { 
    [super encodeWithCoder:aCoder]; 
    [aCoder encodeObject:existingArray]; 
    [aCoder encodeObject:anotherExistingArray]; 

    [aCoder encodeObject:myNewArray]; 
} 

-(id) initWithCoder:(NSCoder *)aDecoder { 
    self = [super initWithCoder:aDecoder]; 
    if(self != nil) { 
     NSArray *_existingArray = [aDecoder decodeObject]; 
     NSArray *_anotherExistingArray = [aDecoder decodeObject]; 

     // We crash here, this object doesn't exist in documents saved with only the first two arrays 
     NSArray *_myNewArray = [aDecoder decodeObject]; 
    } 
    return(self); 
} 

我不認爲我可以將此轉換爲密鑰歸檔和保持與先前保存的檔案兼容性(這是一個要求)。試圖捕捉拋出的異常似乎也沒有幫助。

任何想法?

UPDATE:Bah,爲什麼當你問一個問題時你幾乎馬上就能自己找到答案?

該課程版本正確。以前的作者在版本檢查中有一個錯誤。因此完整性:

+ (void) initialize { 
    if(self == [MyClass class]) { 
     [self setVersion:2]; // was 1 
    } 
} 

-(void) encodeWithCoder:(NSCoder *)aCoder { 
    [super encodeWithCoder:aCoder]; 
    [aCoder encodeObject:existingArray]; 
    [aCoder encodeObject:anotherExistingArray]; 
    [aCoder encodeObject:myNewArray]; 
} 

-(id) initWithCoder:(NSCoder *)aDecoder { 
    self = [super initWithCoder:aDecoder]; 
    int version = [aDecoder versionForClassName:@"MyClass"]; 
    if(self != nil) { 
     NSArray *_existingArray = [aDecoder decodeObject]; 
     NSArray *_anotherExistingArray = [aDecoder decodeObject]; 

     if(version > 1) { 
      NSArray *_myNewArray = [aDecoder decodeObject]; 
     } 
    } 
    return(self); 
} 

回答

1

繼續使用串行存檔器讀取舊文件(只讀)。
加載和保存密鑰歸檔的新文件,檢測方式:

[NSCoder allowsKeyedCoding] 
+0

接受馬克的回答,因爲它是一個相當不錯的主意,如果你的對象是不正確版本。 – MyztikJenz 2011-05-15 05:49:54