gpt4 book ai didi

iOS NSKeyedArchiver unarchive 返回空数组

转载 作者:行者123 更新时间:2023-11-28 22:26:01 28 4
gpt4 key购买 nike

我在使用 NSKeyedArchiver 时遇到了一个问题,这让我困惑了很长一段时间,而且似乎无法查明错误。

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

- (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 NSKeyedArchiver unarchive 返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18954529/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com