0

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?

Community
  • 1
  • 1
raej2010
  • 117
  • 2
  • 9

1 Answers1

0

Another option would be to write your objects out to a file instead of NSUserDefaults. Check out the answer to this question here for a full code example of how to do that.

Community
  • 1
  • 1
JonahGabriel
  • 3,066
  • 2
  • 18
  • 28