I am trying to save an NSMutableArray to the NSUserDeafults. I have implemented the NSCoding protocol methods as so
-(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;
}
and
-(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"];
}
i save it like this
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:hwArray] forKey:ARRAY_KEY];
and get it like this
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];
}
}
It seems perfect according to this question, yet I can't seem to load it beacuse even though I've put objects into the array and loaded it the array is always nil at another run. Any idea on what's the problem?