问题描述
要从NSUserDefaults
获取值,我将执行以下操作:
To get a value from NSUserDefaults
I would do something like this:
let userDefaults = NSUserDefaults.standardUserDefaults()
if let value = userDefaults.objectForKey(key) {
print(value)
}
但是,这些方法不返回可选值:
However, these methods do not return optionals:
-
boolForKey
(如果未设置,默认为false
) -
integerForKey
(如果未设置,默认为0
) -
floatForKey
(如果未设置,默认为0.0
) -
doubleForKey
(如果未设置,则默认为0.0
)
boolForKey
(defaults tofalse
if not set)integerForKey
(defaults to0
if not set)floatForKey
(defaults to0.0
if not set)doubleForKey
(defaults to0.0
if not set)
在我的应用中,我想使用整数的保存值(如果先前已设置).如果以前没有设置,我想使用自己的默认值.问题是0
是我的应用程序的有效整数值,因此我无法知道0
是先前保存的值还是默认的未设置值.
In my app I want to used the saved value of an integer if it has been previously set. And if it wasn't previously set, I want to use my own default value. The problem is that 0
is a valid integer value for my app, so I have no way of knowing if 0
is a previously saved value or if it is the default unset value.
我将如何处理?
推荐答案
在AppDelegate中注册用户默认值,最好的位置是awakeFromNib
甚至init
.您可以为每个键提供自定义默认值.
Register the user defaults in AppDelegate, the best place is awakeFromNib
or even init
. You can provide custom default values for every key.
override init()
{
let defaults = NSUserDefaults.standardUserDefaults()
let defaultValues = ["key1" : 12, "key2" : 12.6]
defaults.registerDefaults(defaultValues)
super.init()
}
然后,您可以随时随地以非可选方式读取值
Then you can read the values from everywhere always as non-optionals
let defaults = NSUserDefaults.standardUserDefaults()
myVariable1 = defaults.integerForKey("key1")
myVariable2 = defaults.doubleForKey("key2")
这篇关于如何在Swift中处理NSUserDefaults中的非可选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!