在应用退出时保存变量 [英] Saving Variables on app exit

查看:107
本文介绍了在应用退出时保存变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的iPhone应用程序,具有多个视图,并列出了5个不同的项目,这些项目具有附加的变量,无论用户在应用程序中的位置如何,这些变量都将传递给每个新视图.

I have a simple iPhone app in swift with multiple views and a list of 5 different items that have variables attached to them that get passed to each new view no matter where the user is in the app.

示例:

    var Peron1 = String()
    var Person1Age = Int()
    var Person1Switch = Bool()

(想象一下,但是只有5个人)

(Imagine that but for 5 people)

基本上,我想对应用程序进行编程,以便当用户退出并返回到应用程序时,已经恢复了他们输入到应用程序中的变量,然后可以继续对其进行操作.做这个的最好方式是什么?另外,我也不想包含保存"或恢复"按钮.

Basically I want to program the app so when the user quits and returns to the app the variables they have entered into the app already are restored and then can continue to be manipulated. What is the best way to do this? Also I don't want to include a save or restore button.

推荐答案

您可以使用NSUserDefaults并将变量值保存在其中:

You can use NSUserDefaults and save the variable-values in it:

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(Person1, forKey: "Person1")
defaults.setInteger(Person1Age, forKey: "Person1Age")
defaults.setBool(Person1Switch, forKey: "Person1Switch")

然后,即使像这样重新启动应用程序,也可以稍后获得它:

Then you can get it later, even after an app restart like that:

defaults.stringForKey("Person1")
defaults.integerForKey("Person1Age")
defaults.boolForKey("Person1Switch")

如您所见,可以通过使用适合数据类型的方法来访问它.

As you see you can access it by using the fitting methods for your datatype.

这篇关于在应用退出时保存变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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