2014-09-21 74 views
-1

我試圖實現NSCoder方法encodeWithCoder和initWithCoder爲我創建了一個自定義對象具有自定義對象的子數組的自定義對象。這兩個自定義對象都使用上述方法,但在頂層對象解碼之後,數組的值始終爲零。NSCoder不與NSArray

這兩個對象都實現了下面的方法,字典和數組,或者從庫中很受歡迎,我用它來獲取字段名稱並將對象轉換爲字典。我已經檢查過在Array上調用encodeObject,此時該數組不是零。我也有同樣的檢查,解碼方法是收到零在另一邊..

我不能確定我要去哪裏錯了?我正確的假設,只要兒童數組對象實現協議,我應該罰款這樣做?

- (void)encodeWithCoder:(NSCoder *)aCoder{ 
    NSDictionary* dictionary = [jrModelBinder unBind:self]; 
    for(NSString* field in dictionary) 
    { 
     id val = [self valueForKey:field]; 
     [aCoder encodeObject:val forKey:field]; 
    } 
} 

-(id)initWithCoder:(NSCoder *)aDecoder{ 
    if(self = [super init]){ 
     NSArray* fields = [jrModelBinder propertyNames:self]; 
     for(NSString* field in fields) 
     { 
      id val = [aDecoder decodeObjectForKey:field]; 
      [self setValue:val forKey:field]; 
     } 
    } 
    return self; 
} 
+0

不要忘記在'initWithCoder'中調用'[super initWithCoder:]''。 – quellish 2014-09-21 18:37:31

+0

NSObject沒有實現initWithCoder? – 2014-09-21 18:39:12

+0

您的問題中沒有指定 – quellish 2014-09-21 18:45:09

回答

0

我誤解你的問題之前:

的NSKeyedArchiver /取檔應該編碼和解碼NSArrays和NSDictionaries沒有問題。

但是我覺得既然你的陣列本身包含實現以下兩個功能自定義對象:

- (id)initWithCoder:(NSCoder *)aDecoder 
- (void)encodeWithCoder:(NSCoder *)enCoder 

嘗試使用下面的陣列

NSData * encodedData = [NSKeyedArchiver archivedDataWithRootObject:someArray]; 

還可以使用NSKeyedUnarchiver進行解碼。

+0

您可能需要將數據保存在File或NSDefault中。 – bllakjakk 2014-09-21 20:17:49