NSKeyedArchiver在模拟器上工作但不是实际设备

时间:2014-05-28 10:40:06

标签: ios objective-c xcode nskeyedarchiver

我似乎无法让NSKeyedArchiver工作。我有一个主ViewController,它有一个NSMutableArray作为实例变量。该数组由自定义类的多个实例填充。自定义类符合NSCoding协议,并实现编码和解码方法。从主视图控制器,我调用

- (NSString *)itemArchivePath
{
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

//only one document in list - get path t o it
NSString *documentDirectory = [documentDirectories firstObject];

return [documentDirectory stringByAppendingString:@"locations.archive"];
}

- (BOOL)saveChanges
{
//returns success or failure
NSString *path = [self itemArchivePath];

return [NSKeyedArchiver archiveRootObject:myArray //this is the array to archive
                                   toFile:path];
}

在app delegate中,我为applicationDidEnterBackground调用saveChanges方法。该方法在模拟器上返回true,但对于实际设备则返回false。我不知道该怎么做。任何帮助表示赞赏。谢谢!

编辑:根据Zaph的评论,我已将saveChanges方法更改为:

- (void)saveChanges
{
//returns success or failure
NSString *path = [self itemArchivePath];

NSData *dataOfArray = [NSKeyedArchiver archivedDataWithRootObject:myArray];
NSFileManager *checker = [NSFileManager defaultManager];
[dataOfArray writeToFile:path
              atomically:YES];

if ([checker fileExistsAtPath:path]) {
    NSLog(@"Archive Successful");

}
else {
    NSLog(@"Archive Did Not Work");
}

}

1 个答案:

答案 0 :(得分:1)

NSLog路径! @Wolfgang表示,这可能是错误的。

[documentDirectory stringByAppendingString:@"locations.archive"]

不会在路径和文件名之间添加“/”。使用方法:

[documentDirectory stringByAppendingPathComponent:@"locations.archive"]

当代码不起作用时,尽量简化,将复合语句分解为单个语句。然后按照调试器和/或NSLog()语句检查每一步。