Brittany Brittany - 5 months ago 30
iOS Question

Saving NSMutableArray to NSUserDefaults

I have an

NSMutableArray
inside of my
AppDelegate
, and I'm attempting to save it to
NSUserDefaults
. The
NSMutableArray
(strainsfinal) contains a list of favorited items. I want this list to save, and be present even if the app is shut down, and then restarted. Does anyone know why my code isn't working (not saving my data)? See below:

AppDelegate.m

-(void)updateStrains:(NSDictionary *)item
{
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataSave = [currentDefaults objectForKey:@"strains"];
if (strainsfinal != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataSave];
if (oldSavedArray != nil)
strainsfinal = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
strainsfinal = [[NSMutableArray alloc] init];
}

}


EDIT: Appdelegate.m So I've changed my above method to the method below (and I thought it should work), but the app crashes, saying: "Terminating app due to uncaught exception 'NSInvalidArguementException', reason: 'NSConcreteAttributedString initwithString: nil 'value'.

What am I missing?!

-(void)updateStrains:(NSDictionary *)item {

NSData *dataSave = [NSKeyedArchiver archivedDataWithRootObject:strainsfinal];
[[NSUserDefaults standardUserDefaults] setObject:dataSave forKey:@"strains"];
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"arrayupdated" object:self userInfo:nil];
NSLog(@"updated strains %@",strainsfinal);
}

Answer

You must add

[currentDefaults synchronize];

each time after you save something to userDefaults;

But for such kind of data is better to use .plist files. Check documentation for more info.

EDITED Code:

-(void)updateStrains:(NSDictionary *)item {
    NSData *dataSave = [NSKeyedArchiver archivedDataWithRootObject:item[@"strainsfinal"]];
    [[NSUserDefaults standardUserDefaults] setObject:dataSave forKey:@"strains"];
   // NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
   // [nc postNotificationName:@"arrayupdated" object:self userInfo:nil];
    NSLog(@"updated strains %@",strainsfinal);   
    [[NSUserDefaults standardUserDefaults] synchronize]; // this will save you UserDefaults
}