本文介绍了首次安装应用程序时存储变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首次安装应用时尝试存储变量 DateInstalled ,但每次应用加载此变量时,新日期都会覆盖此变量。

Attempting to store the variable DateInstalled when the app is first installed, but each time the app loads this variable is overridden by the new date.

我是 Xcode 的新手,所以答案可能很明显。我发现下面的代码将变量存储在用户默认值中,但每次它似乎跳到else语句。

I am new to Xcode so the answer is probably obvious. I found this code below to store the variable in the user defaults but every time it seems to skip to the else statement.

var DateInstalled: NSDate {
    get {
        if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey("DateInstalled") as? NSDate {
            return returnValue
        } else {
            NSLog("Saving new Date")
            return NSDate()          // Default value
        }
    }
    set {
        NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "DateInstalled")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}


推荐答案

嘿@Curtis Cowan试试这个

Hey @Curtis Cowan try with this

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

            let firstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunchTime")
            if firstLaunch  {
               println("Not First launch")
            }
            else {
                println("First launch")
                NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey:"FirstLaunchTime")
                 }

            return true
      }

这篇关于首次安装应用程序时存储变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 09:30