简体   繁体   English

如何在每次运行应用程序时更改 NSUserDefault 的默认返回值而不保存它

[英]How to change the default return value of an NSUserDefault without saving it every time the app is run

I'm using a Bool UserDefault that I want to initially return as true unless changed elsewhere in the app.我正在使用Bool UserDefault,除非在应用程序的其他地方发生更改,否则我希望最初将其返回为true Unfortunately, UserDefault.bool(forKey:) returns false until stated otherwise.不幸的是,除非另有说明,否则UserDefault.bool(forKey:)返回false I would set it equal to true in the viewDidLoad() but that would result in it being reset every time that screen is loaded.我会在viewDidLoad()中将它设置为true ,但这会导致每次加载屏幕时都会重置它。

How do I change the initial default return value to true instead of false in swift?如何在 swift 中将初始默认返回值更改为true而不是false

Please use swift if possible.如果可能,请使用 swift。

It isn't totally clear what you are asking.你在问什么并不完全清楚。 Are you asking how to make it so that when your app is first installed and run, the value of your BOOL loads as true?您是在问如何做到这一点,以便在您的应用程序首次安装和运行时,您的 BOOL 值加载为 true?

The answer is to use the registerDefaults() method (as Martin R mentioned in his comment).答案是使用registerDefaults()方法(正如 Martin R 在他的评论中提到的)。

You pass it an NSDictionary containing the key/value pairs that you want to load as your "default defaults".您向它传递一个 NSDictionary,其中包含要作为“默认默认值”加载的键/值对。 The best place to do that is in the initialize class method for your app delegate.最好的地方是在你的应用程序委托的初始化类方法中。 That way the default defaults key value pairs get set before any of your apps other code gets run.这样,在您的任何应用程序其他代码运行之前设置默认默认键值对。

So add this method to your app delegate:因此,将此方法添加到您的应用程序委托中:

class func initialize()
{
  NSUserDefaults.standardUserDefaults().registerDefaults(
    ["myDefault": true,
     "aStringDefault": "defaultStringValue"],
     "arrayDefault": [1, 2, 3,])
  //Do any other startup initialization that needs to happen 
  //before all your other app delegate code.
}

(Not tested. May need minor changes to work...) (未测试。可能需要稍作改动才能工作......)

EDIT:编辑:

You can register as many defaults as you like, and also write more complex structures into defaults.您可以注册任意数量的默认值,也可以将更复杂的结构写入默认值。 I updated the sample code to show a more complex example)我更新了示例代码以显示更复杂的示例)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM