Search code examples
iosnsmutablearraynsuserdefaultsnskeyedarchivernskeyedunarchiver

NSUserDefaults is saving just last value


I have a problem if anyone can help me or can give me an advice whose who faced with similar problem. Ok, I save data in NSUsersDefaults like this

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:getDate];
[defaults setObject:data forKey:@"data"];
[defaults synchronize];

and now when I want to retrieve in this way:

NSData *theData = [[NSUserDefaults standardUserDefaults] objectForKey:@"data"];
NSString *date = (NSString *) [NSKeyedUnarchiver unarchiveObjectWithData:theData];

if (date != nil) {
    NSMutableArray *mutable = [[NSMutableArray alloc] init];
    [mutable addObject:date];
}

is showing just last value, the value is picked from pickerDate. How can I make to save all dates that I'm picking from pickerDate. Thank you very much!!!


Solution

  • The problem is that you're not using the NSMutableDictionary correctly. Look at this code:

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:getDate];
    [defaults setObject:data forKey:@"data"];
    [defaults synchronize];
    

    This means that you will always save the date under the key data. Because you're using a NSString, this means that if there is already an existing entry under data, it will overwrite it. For example:

    The first time you use your app, there is nothing under data saved. I pick "1-20-2015", then my dictionary is:

    { data: "1-20-2015"}

    Now I go and pick another date, "2-21-2015". I already have an entry under data, so this means it updates it to:

    { data: "2-21-2015"}

    See how we erased "1-20-2015"? This is what's happening to you.

    In a Dictionary, keys are unique objects. You need to use an NSMutableArray as the object, or use a unique key for each entry.