Reputation: 174
I am trying to save an array using NSUserDefaults. I have gotten it to work in other parts of my app and I can't seem to figure out why it doesn't work now. It seems that it is adding (null) to the userDefaults-array, but when I NSLog what I am trying to add ([mainDelegate.globalValdaFragor objectAtIndex:i]) I can see the value I want to input.
The problem seems to be that I can't add anything to the "felPaFragor"-array, seeing as when I try to NSLog it I get (null) and when I tried it with another "random" array it worked.
RPAppDelegate *mainDelegate = (RPAppDelegate *)[[UIApplication sharedApplication]delegate];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *felPaFragor = [[NSMutableArray alloc] init];
felPaFragor = [[defaults valueForKey:@"felFragorArray"] mutableCopy];
[felPaFragor addObject:[mainDelegate.globalValdaFragor objectAtIndex:i]];
[defaults setObject:felPaFragor forKey:@"felFragorArray"];
Any help would be greatly appreciated.
Edit: I think I figured it out. It seems I was trying to make a mutableCopy of an empty array and that in turn made my "felPaFragor"-array buggy. Adding this made it work.
felPaFragor = [[NSMutableArray alloc] init];
if ([[defaults valueForKey:@"felFragorArray"] objectAtIndex:0] != NULL) {
felPaFragor = [[defaults valueForKey:@"felFragorArray"] mutableCopy];
}
Upvotes: 0
Views: 873
Reputation: 6176
first: are you using ARC?
if not, you have a memory leak here:
NSMutableArray *felPaFragor = [[NSMutableArray alloc] init];
felPaFragor = [[defaults valueForKey:@"felFragorArray"] mutableCopy];
the first like create and retain a NSMutableArray never released (and never used: you don't need that line at all, ARC or not ARC)
just use:
NSMutableArray *felPaFragor = [[defaults valueForKey:@"felFragorArray"] mutableCopy];
said that, Sergio's answer may be the right one... your valueForKey:@"felFragorArray" may just never been set when you call it at this point
Upvotes: 1
Reputation: 69027
If after executing this:
NSMutableArray *felPaFragor = [[NSMutableArray alloc] init];
felPaFragor = [[defaults valueForKey:@"felFragorArray"] mutableCopy];
your felPaFragor
is nil
, then it is highly likely that [defaults valueForKey:@"felFragorArray"]
is returning nil
.
So, you have a problem with your key, or possibly the object associated to that key has never been stored in NSUserDefaults
yet.
Upvotes: 1