Clearing NSUserDefaults after specified time period iPhone

邮差的信 提交于 2019-12-19 10:23:19

问题


I have created NSUserDefaults object, it will be updated with the new value whenever an even will occur. What I want is (as per my application requirement) that object should be cleared every 7 days. Like if 1st time that NSUserDefaults are updated today so exact after 7 days, a method should work and clear the NSUserDefaults. So that, new values would be assigned from then on for the next 7 days.

Is it possible in objective-c?


回答1:


What you can do is store an NSDate object. Then every time the application is launched (or more often) check if the time difference between then and now is 7 days.

const NSString *kFirstLaunchDateKey = @"firstLaunchDate";
NSDate *firstLaunchDate = [[NSUserDefaults standardUserDefaults] objectForKey:kFirstLaunchDateKey];

//  If this is the first time the app has been launched we record right now as the first time the app was launched.
if (!firstLaunchDate) {
    [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:kFirstLaunchDateKey];
    return;
}

NSTimeInterval *diff = abs([firstLaunchDate timeIntervalSinceNow]);
if (diff > 60 * 60 * 24 * 7) {
//      Seven days have passed since the app was first launched. 
//      Display the rate button.
}

If it is call

- (void)removePersistentDomainForName:(NSString *)domainName

With your application’s bundle identifier as the parameter.

From Apple’s documentation:

domainName The domain whose keys and values you want. This value should be equal to your application's bundle identifier.




回答2:


yes.. store the NSDate(current Date) as an object in NSUserdefaults.

At every launch of your app.. get the date from the defaults and compare it to current Date..

If the interval is more than 7 days(you will have to do math calculation to get the result)

then set the object as nil

using

[defaults setNilforKey: ];


来源:https://stackoverflow.com/questions/9684900/clearing-nsuserdefaults-after-specified-time-period-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!