调试Archiver

时间:2014-05-27 15:26:57

标签: ios objective-c nskeyedarchiver persistent-data

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

//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];
}

关于数组的注释不在实际代码中。最后,app delegate具有以下代码:

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

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

}

不幸的是,无论何时运行代码,都会记录“不成功”,我不知道为什么。 mainViewController是app delegate的实例变量。我已经尝试了很长时间的调试,我找不到问题。任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

您尝试保存的path很有可能无效。您应该尝试记录它,并在保存失败时查看值是否合理。您可能还希望使用stringByAppendingPathComponent:代替stringByAppendingString: