我遇到了NSKeyedArchiver的问题,现在已经困扰了我很长一段时间,似乎无法查明错误。
我有一个由类“Device”的对象组成的可变数组。 在我的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;
}
我一直从unarchiving过程中获得一个空的mutableArray。我正在使用ARC,不确定它是否与它有任何关系。
答案 0 :(得分:2)
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");
}