Saving variables and booleans in swift 3 [closed]

2019-10-04 22:45发布

问题:

I'm new to iOS development, currently in the process of creating my first app which its core function is a timer

I have a few different variables (for example start time of timer) and a boolean of whether the timer is running or not.

Is there a way where I can save the timer start time or boolean values even when the app is closed?

I'm using NSDate to store the start time and comparing the current time to this in order to produce a value of time passed.

Thanks in advance!

回答1:

Swift 3.x

Set and get the Date object

UserDefaults.standard.set(Date(), forKey: "lastDate")
UserDefaults.standard.object(forKey: "lastDate") as? Date

Set and get the Bool object

UserDefaults.standard.set(true, forKey: "isOn")
UserDefaults.standard.bool(forKey: "isOn")