iOS - 无法将NSDate存储到NSUserDefaults中 [英] iOS - Not able to store NSDate into NSUserDefaults

查看:114
本文介绍了iOS - 无法将NSDate存储到NSUserDefaults中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我想首次存储应用程序启动的日期。

我在应用程序中使用以下代码:didFinishLaunchingWithOptions方法

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?

推荐答案

因为你的目标是第一次跟踪用户启动你的应用程序,在应用程序中你需要这样的东西:didFinishLaunchingWithOptions

Since your goal to is keep track of the very first time a user starts your app, you need something like this in 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);

这篇关于iOS - 无法将NSDate存储到NSUserDefaults中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆