我无法弄清楚我的归档和取消归档有什么问题。我正在尝试保存类中的数据。编码器和解码器是:
//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 是应用程序委托的实例变量。我调试了很长时间,也找不到问题所在。任何帮助表示赞赏。谢谢!