简体   繁体   中英

Save NSMutableArray to NSUserDefaults - problems with adding object

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];
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM