ios Swift - 如何为 NSUserDefaults 设置初始值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37830558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift - How to set initial value for NSUserDefaults
提问by Big Green Alligator
I have a switch called soundSwitch, I am saving the state of the button using an user default as such:
我有一个名为 soundSwitch 的开关,我使用用户默认值保存按钮的状态,如下所示:
@IBAction func soundsChanged(sender: AnyObject) {
if soundSwitch.on{
defaults.setBool(true, forKey: "SoundActive")
print("Sound ON")
}else{
defaults.setBool(false, forKey: "SoundActive")
print("Sound OFF")
}
}
Currently the actual defaults value is initially false when the user first launches the application.
当前,当用户首次启动应用程序时,实际默认值最初为 false。
How do I implement the defaults to be true if the user is first launching the app and it they haven't been configured yet.
如果用户第一次启动应用程序并且尚未配置它们,我如何将默认设置设为 true。
I have seen methods in Objective-C, but nothing in Swift. From what I have seen you can do it in the app delegate some how, or in a plist file. How do I do either of those ones?
我在 Objective-C 中见过方法,但在 Swift 中没有。根据我所见,您可以在应用程序委托中以某种方式或在 plist 文件中执行此操作。我该怎么做?
回答by Novi
Swift 3 syntax example
Swift 3 语法示例
Register a boolean default value:
注册一个布尔默认值:
UserDefaults.standard.register(defaults: ["SoundActive" : true])
And to getthe value:
并获得价值:
UserDefaults.standard.bool(forKey: "SoundActive")
Sidenote: Although the above code will return true, note that the value isn't actually written to disk until you setit:
旁注:虽然上面的代码将返回 true,但请注意,在设置之前,该值实际上不会写入磁盘:
UserDefaults.standard.set(true, forKey: "SoundActive")
回答by fs_tigre
Add this to your didFinishLaunchingWithOptions
method from the AppDelegate. As some others pointed out try not to abuse by putting everything in this method.
didFinishLaunchingWithOptions
从 AppDelegate将其添加到您的方法中。正如其他一些人指出的那样,尽量不要通过将所有内容都放在这种方法中来滥用。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
/// Here you can give default values to your UserDefault keys
UserDefaults.standard.register(defaults: [
"SoundActive": true,
"someOtherKey": "Some Message"
])
}
回答by Guy Brooker
Swift 4
斯威夫特 4
I prefer to implement a function similar to UserDefaults.string(forKey: )
which returns nil
if the value is not set. Combined with the ?? operator, you don't need to have any default values written to disk unless you explicitly set them later.
我更喜欢实现一个类似于如果未设置值则UserDefaults.string(forKey: )
返回的函数nil
。结合?? 操作符,您不需要将任何默认值写入磁盘,除非您稍后明确设置它们。
extension UserDefaults {
public func optionalInt(forKey defaultName: String) -> Int? {
let defaults = self
if let value = defaults.value(forKey: defaultName) {
return value as? Int
}
return nil
}
public func optionalBool(forKey defaultName: String) -> Bool? {
let defaults = self
if let value = defaults.value(forKey: defaultName) {
return value as? Bool
}
return nil
}
}
Then you can retrieve your default values as follows
然后您可以按如下方式检索默认值
let defaults = UserDefaults.standard
let userName = defaults.string(forKey: "Username") ?? "Happy"
let userAge = defaults.optionalInt(forKey: "Age") ?? 21
let isSmart = defaults.optionalBool(forKey: "Smart") ?? true
回答by Hardik Thakkar
Using "registerDefaults" you can set Default value of NSUserDefaults
使用“registerDefaults”,您可以设置 NSUserDefaults 的默认值
let userDefaultsDefaults = [
"SoundActive" : true
]
NSUserDefaults.standardUserDefaults().registerDefaults(userDefaultsDefaults)
Note: write this in didFinishLaunchingWithOptions, so default value is set.
注意:在 didFinishLaunchingWithOptions 中写这个,所以设置了默认值。
write below code where you want to check
在下面要检查的地方写下代码
let onoroff = NSUserDefaults.standardUserDefaults().objectForKey("SoundActive") as! Bool!
if (onoroff != nil && onoroff == false)
{
self.checkForAgreement()
}
回答by Wain
There is nothing swift or app delegate specific.
没有任何特定的 swift 或应用程序委托。
Initial defaults are set by calling registerDefaults:
on the standardUserDefaults
instance.
初始默认值是通过调用设置registerDefaults:
的standardUserDefaults
实例。
You can make this call multiple times and I'd recommend that you don't do it in the app delegate, instead register appropriate details at appropriate times in the app, so if you have 1 view controller / subsystem which uses certain defaults values then register the default values as part of the initialisation if that code.
您可以多次进行此调用,我建议您不要在应用程序委托中执行此操作,而是在应用程序中的适当时间注册适当的详细信息,因此如果您有 1 个使用某些默认值的视图控制器/子系统如果该代码,则将默认值注册为初始化的一部分。
Only if you have something which is used by multiple different parts of the code should you consider doing that in the app delegate, and then only if you don't have some other appropriate controller in which to do it.
只有当你有一些东西被代码的多个不同部分使用时,你才应该考虑在应用程序委托中这样做,然后只有当你没有其他合适的控制器来做到这一点时。
回答by Klein Mioke
func lastStatus() -> Bool {
let defaultValue = true
if let value = default.valueForKey("SoundActive") {
// then use it
return value as? Bool ?? defaultValue
} else {
// oh, no value?
return defaultValue
}
}
I think this is best way of using it. Also register(defaults:)
will help, but in documentation Apple suggest to using it as fallback
, like separating situation of no value
and default value
. Depend on your need.
我认为这是使用它的最佳方式。也register(defaults:)
将有所帮助,但在文档中苹果建议使用它fallback
,就像分离的情况no value
和default value
。取决于你的需要。
回答by Robin Stewart
You can encapsulate all of your UserDefaults
logic into a property variable that automatically registers the application default and saves any updates back into the user defaults dictionary. This is especially convenient if other parts of the app (besides the switch control) also read or change this state.
您可以将所有UserDefaults
逻辑封装到一个属性变量中,该变量会自动注册应用程序默认值并将任何更新保存回用户默认值字典。如果应用程序的其他部分(除了开关控制)也读取或更改此状态,这将特别方便。
Swift 5— The first part executes a closure to initialize the property, and the second part is the didSet
block which is called automatically any time the property is changed.
Swift 5——第一部分执行一个闭包来初始化属性,第二部分是didSet
在属性改变时自动调用的块。
var soundIsActive: Bool = {
// Register the app default:
UserDefaults.standard.register(defaults: ["SoundActive" : true])
// Initialize the property with the current user default:
return UserDefaults.standard.bool(forKey: "SoundActive")
}()
{
didSet {
// Update user default when the variable is set:
UserDefaults.standard.set(soundIsActive, forKey: "SoundActive")
}
}
回答by Dominic
If you really want to do it this way, put this in the AppDelegate:
如果你真的想这样做,把它放在 AppDelegate 中:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.valueForKey("SoundActive") == nil {
defaults.setBool(true, forKey: "SoundActive")
}
If it is just used in the one viewcontroller, consider putting the code in the viewDidLoad method instead!
如果只是在一个viewcontroller中使用,可以考虑把代码放在viewDidLoad方法中!
回答by AMAN77
Put this in your "didFinishLaunchingWithOptions" in your AppDelegate.
把它放在你的 AppDelegate 的“didFinishLaunchingWithOptions”中。
if defaults.valueForKey("launchedAlready") == true {
print("Not first launch.")
}
else {
defaults.setValue(true, forKey: "launchedAlready")
defaults.setBool(true, forKey: "SoundActive")
print("Sound ON")
}