0

我遇到了 NSKeyedArchiver 的问题,这让我困惑了很长时间,似乎无法查明错误。

我有一个由“设备”类的对象组成的可变数组。在我的 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,不确定这是否与它有关。

4

1 回答 1

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");
}
于 2013-09-23T08:36:40.533 回答