我正在尝试将一个包含5个数据对象的自定义对象的可变数组写入磁盘。但是,使用unarchiver总是使我的数组变为null,我无法弄清楚原因。这是方法:( self.toDoItems是在这个类中定义的NSMutableArray)
- (void)viewDidLoad {
[super viewDidLoad];
self.toDoItems = [[NSMutableArray alloc] init];
NSLog(@"toDOitems on load = %@",self.toDoItems);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"deliveries.txt"];
self.toDoItems = [NSKeyedUnarchiver unarchiveObjectWithFile:appFile];
NSLog(@"toDOitems after unarchive = %@",self.toDoItems);
[self loadInitialData1];
//load array here
}
这是输出:
2015-06-28 17:15:07.778 ToDoList[13493:645560] toDOitems on load = (
)
2015-06-28 17:15:07.780 ToDoList[13493:645560] toDOitems after unarchive = (null)
2015-06-28 17:15:07.780 ToDoList[13493:645560] toDOitems = (null)
2015-06-28 17:18:42.498 ToDoList[13493:647529]
这是NSCoding的实现:
#import "ToDoItem.h"
@implementation ToDoItem
-(void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeObject:self.total forKey:@"total"];
[encoder encodeObject:self.tip forKey:@"tip"];
[encoder encodeObject:self.percentage forKey:@"percentage"];
[encoder encodeBool:self.completed forKey:@"completed"];
[encoder encodeBool:self.isCreditCard forKey:@"isCreditCard"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
self.total = [decoder decodeObjectForKey:@"total"];
self.tip = [decoder decodeObjectForKey:@"tip"];
self.percentage = [decoder decodeObjectForKey:@"percentage"];
self.completed = [decoder decodeBoolForKey:@"completed"];
self.isCreditCard = [decoder decodeBoolForKey:@"isCreditCard"];
}
return self;
}
@end