iosapplication-state

iPhone setting NSUserDefaults to nil when app is closed or in background


I want to eliminate all of the variables saved into all fields of NSUserDefaults whenever the app is closed or running in the background for a certain amount of time - say 5 minutes.

I tried to add a line to the app delegate of applicationDidFinishLaunching that looks like this:

if (UIApplicationStateBackground == TRUE) {
    NSUserDefaults *profiles = [NSUserDefaults standardUserDefaults];

    [profiles setObject:nil forKey:@"name1"];
    [profiles synchronize];
}

I also added just this portion to the applicationWillTerminate:

NSUserDefaults *profiles = [NSUserDefaults standardUserDefaults];

    [profiles setObject:nil forKey:@"name1"];
    [profiles synchronize];

None of this seems to be working and I have no idea how to set a condition of 'if 5 minutes have surpassed of the application being in the background, delete the NSUserDefaults variables' - Any help?


Solution

  • I would recommend to remove the object instead of setting it to nil.

    - (void)removeObjectForKey:(NSString *)defaultName;
    

    The normal behavior of NSUserDefaults is to return nil when there is no key matching the query, so I believe is better to follow the same rule and not store nil for a certain key.

    Hope it helps.