2012-03-13 27 views
2

我已經創建了NSUserDefaults對象,每當發生偶數事件時它都會更新爲新值。 我想要的是(根據我的應用程序要求)該對象應該每7天清除一次。 就像第一次NSUserDefaults在7天后如此精確地更新一樣,一個方法應該可以工作並清除NSUserDefaults。 因此,在接下來的7天內將會分配新的值。在指定的時間段後清除NSUserDefaults iPhone

在objective-c中可能嗎?

回答

2

你可以做的是保存一個NSDate對象的對象爲無

。然後每次啓動應用程序(或更頻繁)檢查時間和現在之間的時間差是否爲7天。

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. 
} 

如果調用

- (void)removePersistentDomainForName:(NSString *)domainName 

與應用程序的包標識作爲參數。

From Apple’s documentation:

domainName 您想要它的鍵和值。該值應該等於您的應用程序的包標識符。

4

是..將NSDate(當前日期)作爲對象存儲在NSUserdefaults中。

在每次啓動您的應用程序..得到默認的日期,並將其與當前的日期..

如果間隔超過7天(你將不得不做數學計算得到的結果)

然後設置使用

[defaults setNilforKey: ];