【问题标题】:Debugging Archiver调试存档器
【发布时间】:2014-05-27 15:26:57
【问题描述】:

我无法弄清楚我的归档和取消归档有什么问题。我正在尝试保存类中的数据。编码器和解码器分别是:

//archiving
- (void)encodeWithCoder:(NSCoder *)aCoder
{
//encode only certain instance variables
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.location forKey:@"location"]; 


}

- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [self init];
if (self) {
    //decode data
    [self setName:[aDecoder decodeObjectForKey:@"name"]];
    [self setLocation:[aDecoder decodeObjectForKey:@"location"]];

}

return self;

}

实例变量是属性,它们是自定义类的值。此类的多个实例填充存储在我的主视图控制器中的 NSMutableArray。

我的视图控制器包含方法:

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

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

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

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

return [NSKeyedArchiver archiveRootObject:customClassArray //This is the array storing multiple instances of the custom class
                                   toFile:path];
}

关于数组的注释不在实际代码中。最后,应用委托具有以下代码:

- (void)applicationDidEnterBackground:(UIApplication *)application
{

BOOL success = [mainViewController saveChanges];
if (success) {
    NSLog(@"Saved Successfully!");
}
else {
    NSLog(@"Unsuccessful");
}

}

不幸的是,每当运行代码时,总是会记录“不成功”,我不知道为什么。 mainViewController 是应用程序委托的实例变量。我调试了很长时间,也找不到问题所在。任何帮助表示赞赏。谢谢!

【问题讨论】:

  • self.location和self.name有哪些类型?
  • self.location 是一个由 CLLocationManager 确定的 CLLocation 对象。 Self.name 是一个 NSString。
  • 您是否检查过您尝试写入的path 是否正常?
  • 路径看起来不错。当我通过模拟器运行应用程序时,方法会记录“已成功保存!”但是,在实际设备上,我一直收到“不成功”。实际设备上的文档目录路径是否可能不同?
  • 看起来不太可能,但确实有可能——我会尝试在 NSString *path = [self itemArchivePath]; 之后记录 path 的值,看看它在设备上是否正确。

标签: ios objective-c nskeyedarchiver persistent-data


【解决方案1】:

您尝试保存的path 很有可能是无效的。您应该尝试记录它并查看保存失败时该值是否正常。您可能还想看看使用stringByAppendingPathComponent: 而不是stringByAppendingString:。

【讨论】:

    猜你喜欢
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 2021-08-18
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 2022-12-16
    相关资源
    最近更新 更多