【问题标题】:Clearing NSUserDefaults after specified time period iPhone在指定时间段 iPhone 后清除 NSUserDefaults
【发布时间】:2012-03-29 21:43:18
【问题描述】:

我已经创建了 NSUserDefaults 对象,只要发生偶数,它就会被更新为新值。 我想要的是(根据我的应用程序要求)应该每 7 天清除一次对象。 就像今天第一次更新 NSUserDefaults 一样,在 7 天之后如此精确,一个方法应该可以工作并清除 NSUserDefaults。 因此,将从那时起为接下来的 7 天分配新值。

在objective-c中可以吗?

【问题讨论】:

    标签: iphone objective-c xcode cocoa-touch xcode4.2


    【解决方案1】:

    你可以做的是存储一个 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 您想要其键和值的域。此值应等于您的应用程序的包标识符。

    【讨论】:

      【解决方案2】:

      是的.. 将NSDate(当前日期) 作为对象存储在NSUserdefaults 中。

      每次启动您的应用时..从默认值中获取日期并将其与当前日期进行比较..

      如果间隔超过 7 天(你必须做数学计算才能得到结果)

      然后将对象设置为nil

      使用

      [defaults setNilforKey: ];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-07
        • 1970-01-01
        • 2023-04-06
        • 2012-06-17
        • 2021-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多