【问题标题】:NSKeyedArchiver working on simulator but not actual deviceNSKeyedArchiver 在模拟器上工作,但不是在实际设备上工作
【发布时间】:2014-05-28 10:40:06
【问题描述】:

我似乎无法让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];
}

在应用程序委托中,我为 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");
}

}

【问题讨论】:

  • 模拟器不区分大小写,但实际设备。所以检查“locations.archive”的拼写。
  • 我在return语句中创建文件locations.archive。每次我引用路径时,我都会调用 itemArchivePath,所以除了第一次之外,我从来没有真正输入过 locations.archive。我不知道文件的拼写在哪里可能不同。
  • 分两步尝试存档,确定是存档问题还是写入问题。第一次使用:archivedDataWithRootObject:,如果成功写入writeToFile:path atomically:
  • @Zaph 谢谢你!请检查我的编辑。我的代码仍然有问题。
  • 您可能必须使用-stringByAppendingPathComponent: 来创建正确的路径(无论如何处理路径时都应使用此方法)。

标签: ios objective-c xcode nskeyedarchiver


【解决方案1】:

NSLog 路径!正如@Wolfgang 所说,这可能是错误的。

[documentDirectory stringByAppendingString:@"locations.archive"]

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

[documentDirectory stringByAppendingPathComponent:@"locations.archive"]

当代码不工作时,尽量简化,将复合语句分解成单独的语句。然后跟随调试器和/或NSLog() 语句检查每一步。

【讨论】:

  • 谢谢!我检查了 NSLog,这是路径问题。我在路径和位置之间缺少“/”。存档
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 2023-03-23
  • 1970-01-01
  • 2010-11-01
相关资源
最近更新 更多