user2893370
user2893370

Reputation: 711

NSUserDefaults clears its value after specific time

I save my dictionary using NSUserDefaults as follow:

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

// unarchive
NSData *newData = [[NSUserDefaults standardUserDefaults] objectForKey:@"key"];
NSDictionary *newDict = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Problem: The dicitionary contains a name value with some other values, but after specific time period (mostly after 24 Hours), the name values gives me " "(blank) value.

I see this kind of issue first time, help me to solve this.
Thank you.

Upvotes: 0

Views: 290

Answers (2)

Danial Hussain
Danial Hussain

Reputation: 2530

I think you place your code where it is called again after you save for first time and load next time but then your nsdata object is empty.

Scenario :

1st time run app it will save the prefrences

Close the application completely.and then again open your application it again save prefrences while your nsdata object is empty

Edit

Why you not save dictionary directly in NSUserDefaults?

Upvotes: 0

l0gg3r
l0gg3r

Reputation: 8954

The problem is not in this pice of code.

1) Try to check if your application contains [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"key"] in another classes/methods.

2) Check if NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary]; is not empty when you are writing it (Maybe it get's corrupted, and wipes the already written data).
To check the issue you can make a small versioning and debug the issue, here is the code.

    NSMutableArray *datas = [[[NSUserDefaults standardUserDefaults] objectForKey:@"datas"] mutableCopy];
    if (!datas) {
        datas = [NSMutableArray new];
    }
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary];
    [datas addObject:data];
    [[NSUserDefaults standardUserDefaults] setObject:datas forKey:@"datas"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    // Debug code to see the result
    NSLog(@"======= Logging saved datas");
    for (NSData *data in datas) {
        NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        NSLog(@"%@", dict);
    }

This code will allow you to see all the versions of dictionaries saved in NSUserDefaults, and probably you will get the moment when Empty data is saved.

Upvotes: 1

Related Questions