我遇到了一个与NSKeyedArchiver有关的问题,该问题已经困扰了我一段时间,而且似乎无法查明错误。

我有一个由“设备”类的对象组成的可变数组。
在我的appDelegate中,我保留了一个mutableDevicesArray,并且具有以下三个功能:

- (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,不确定是否与此有关。

最佳答案

显然,我不知道您必须首先将根对象(在这种情况下为数组)保存到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");
}

关于ios - iOS NSKeyedArchiver取消归档将返回空数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18954529/

10-12 14:49