Not able to store NSDate into NSUserDefaults

In my application, i want to store the date at which the app is started for the first time.
I'm using following code in application:didFinishLaunchingWithOptions method

NSDate* today = [NSDate date];
[[NSUserDefaults standardUserDefaults] registerDefaults: @{@"CONSCIENCE_START_DATE" : today}];

NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"CONSCIENCE_START_DATE"]);

But every time when i start the application, its printing the time at which the app is starting. Its not printing the date at which i started the app.

I tried to reset the simulator and ran the code again. Still no success. Can some one point me the error in my code please?


由于您的目标是跟踪用户第一次启动您的应用程序,因此在application:didFinishLaunchingWithOptions需要如下所示application:didFinishLaunchingWithOptions

NSDate *date = [[NSUserDefaults standardUserDefaults] objectForKey:@"CONSCIENCE_START_DATE"];
if (!date) {
    // This is the 1st run of the app
    date = [NSDate date];
    [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"CONSCIENCE_START_DATE"]; // Save date
}

NSLog(@"First run was %@", date);

You need to call [[NSUserDefaults standardDefaults] synchronize] after you set the value.

From the Apple Docs:

At runtime, you use an NSUserDefaults object to read the defaults that your application uses from a user's defaults database. NSUserDefaults caches the information to avoid having to open the user's defaults database each time you need a default value. The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with

a user's defaults database.


You Can store and retrieve in this way

var startDate: NSDate? {

    get {
        return NSUserDefaults.standardUserDefaults().objectForKey(BCGConstants.UserDefaultsKey.startDateKey) as? NSDate
    }

    set {
        NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: BCGConstants.UserDefaultsKey.startDateKey)
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}
链接地址: http://www.djcxy.com/p/85176.html

上一篇: iOS NSDate和NSDateFormatter行为

下一篇: 无法将NSDate存储到NSUserDefaults中