开发者

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

开发者 https://www.devze.com 2023-01-14 16:31 出处:网络
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 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 variable开发者_如何转开发s' - Any help?


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.


Maybe you should use applicationDidEnterBackground:. Check out this apple doc page.


I would do the following: in the delegate call - (void)applicationWillResignActive:(UIApplication *)application of UIApplication I would save a timestamp when the application entered the background. In this case you do not have to check if the application is going to the background or if it just got interrupted by e.g. an SMS but the user hit cancel and continues using your application.

When the application launches again implement code in another delegate method of UIApplication - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions to determine how long you have been inactive and wipe the UserDefaults or not depending on the duration.

For more information of application becoming inactive and relaunching check this document of Apple's documentation http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/CoreApplication/CoreApplication.html#//apple_ref/doc/uid/TP40007072-CH3-SW10

0

精彩评论

暂无评论...
验证码 换一张
取 消