2013-09-23 51 views
0

我遇到了NSKeyedArchiver的一個問題,它已經困擾了我很長一段時間,似乎無法查明錯誤。iOS NSKeyedArchiver unarchive返回空數組

我有一個可變數組,由類「設備」的對象組成。 在我的appDelegate我能保證設備的mutableArray,我有以下三個功能:

- (void) loadDataFromDisk { 
    self.devices = [NSKeyedUnarchiver unarchiveObjectWithFile: self.docPath]; 
    NSLog(@"Unarchiving"); 
} 

- (void) saveDataToDisk { 
    NSLog(@"Archiving"); 
    [NSKeyedArchiver archiveRootObject: self.devices toFile: self.docPath]; 
} 

- (BOOL) createDataPath { 
    if (docPath == nil) { 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES); 
     NSString *docsDir = [paths objectAtIndex:0]; 
     self.docPath = [docsDir stringByAppendingPathComponent: @"devices.dat"]; 
     NSLog(@"Creating path"); 
    } 

    NSLog(@"Checking path"); 

    NSError *error; 
    BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath: docPath withIntermediateDirectories: YES attributes: nil error:&error]; 
    if (!success) { 
     NSLog(@"Error creating data path: %@", [error localizedDescription]); 
    } 
    return success; 
} 

我一直在解檔過程中得到一個空mutableArray。我正在使用ARC,並不確定這與它有什麼關係。

回答

2

因此,顯然,我不知道的是,您必須首先將您的根對象(本例中爲數組)保存到NSMutableDictionnary。

NSMutableDictionary *rootObject; 
rootObject = [NSMutableDictionary dictionary]; 

[rootObject setValue: self.devices forKey: @"devices"]; 

然後用NSKeyedArchiver保存rootObject。奇怪的是,在任何教程中都沒有看到。

因此,您最終得到以下用於加載和保存數據到NSKeyedArchiver的函數。

- (void) loadArrayFromArchiver { 
    NSMutableDictionary *rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile: [self getDataPath]]; 

    if ([rootObject valueForKey: @"devices"]) { 
     self.devices = [rootObject valueForKey: @"devices"]; 
    } 

    NSLog(@"Unarchiving"); 
} 

- (void) saveArrayToArchiver { 
    NSLog(@"Archiving"); 

    NSMutableDictionary *rootObject = [NSMutableDictionary dictionary]; 

    [rootObject setValue: self.devices forKey: @"devices"]; 

    [NSKeyedArchiver archiveRootObject: rootObject toFile: [self getDataPath]]; 
} 

- (NSString *) getDataPath { 
    self.path = @"~/data"; 
    path = [path stringByExpandingTildeInPath]; 
    NSLog(@"Creating path"); 
} 
+0

嗨,感謝分享這個,我有同樣的問題,但我不明白答案:(...根對象是一個字典,你把它放在數組中,對於關鍵的權利?那麼當你正在取消存檔時,你會將其解壓縮到字典或數組中? – ColdSteel

+0

我包含了完整的功能,希望對您有所幫助 –

+0

非常感謝!*豎起大拇指* – ColdSteel