我正在尝试将NSMutableArray保存到NSUserDeafults。我已经实现了NSCoding协议方法
-(id)initWithCoder:(NSCoder*)aDecoder{
self = [super init];
if(self!= nil){
self.subject = [aDecoder decodeObjectForKey:@"subj"];
self.notes = [aDecoder decodeObjectForKey:@"notes"];
self.dateDue = [aDecoder decodeObjectForKey:@"date"];
self.done = [[aDecoder decodeObjectForKey:@"done"] boolValue];
self.importancy = [aDecoder decodeObjectForKey:@"imp"];
}
return self;
}
和
-(void)encodeWithCoder:(NSCoder*)enCoder{
[enCoder encodeObject:self.subject forKey:@"subj"];
[enCoder encodeObject:self.notes forKey:@"notes"];
[enCoder encodeObject:self.dateDue forKey:@"date"];
[enCoder encodeObject:self.importancy forKey:@"imp"];
[enCoder encodeObject:[NSNumber numberWithBool:self.done] forKey:@"done"];
}
我像这样保存
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:hwArray] forKey:ARRAY_KEY];
并且像这样得到它
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *hwData = [currentDefaults objectForKey:ARRAY_KEY];
if (hwData != nil)
{
NSLog(@"data is not nil");
NSArray *savedHWArray = [NSKeyedUnarchiver unarchiveObjectWithData:hwData];
if (savedHWArray != nil){
NSLog(@"initiating array");
hwArray = [[NSMutableArray alloc] initWithArray:savedHWArray];
NSLog(@"hw array count: %i",[hwArray count]);
}
else{
hwArray = [[NSMutableArray alloc] init];
}
}
根据this question看起来很完美,但即使我已经将对象放入数组并加载它,数组在另一次运行中总是为零,我似乎无法加载它。关于问题是什么的任何想法?