用户默认值未注册新密钥?
User Defaults is not registering new keys?
我正在设计一个应用程序 (iOS),我正在尝试使用 UserDefaults (Swift 3,Xcode 8.3.3)。我之前添加了一些运行良好的键和值。
但是,当我添加更多密钥时,旧密钥仍然有效,但新密钥无效。具体来说,每当我尝试读取新密钥时,它们都会返回 0。
我已经搜索 Google 和 SO 很多年了,但仍然找不到我哪里出错了。
请帮忙!
在AppDelegate.swift
func applicationDidFinishLaunching(_ application: UIApplication) {
let d = UserDefaults.standard
let defaultValues = ["highScore" : 0,
"second" : 0,
"third" : 0,
"balls" : 0,
"maxLives" : 5,
"increaseML" : 250]
d.register(defaults: defaultValues)
}
在 MenuScene.swift(自定义 class)
var maxLives = defaults.integer(forKey: "maxLives")
var increaseML = defaults.integer(forKey: "increaseML")
出于某种原因,increaseML
和 maxLives
返回 0,即使我将它们的值分别设置为 250 和 5。
为什么会发生这种情况,我该如何解决?
我怀疑你的 applicationDidFinishLaunching
没有被调用。如果您使用 Storyboards
,可能是因为您的 Appdelegate
没有正确连接。
您可以按照此 修复它或将默认值的初始化移动到:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
每次启动应用程序时将调用什么。
此外,Apple 甚至不鼓励您在 this documentation 中使用 applicationDidFinishLaunching(_:)
。
令 d = UserDefaults.standard
let defaultValues = ["highScore" : 0,
"second" : 0,
"third" : 0,
"balls" : 0,
"maxLives" : 5,
"increaseML" : 250]
d.register(defaults: defaultValues)
d.synchronize()
我正在设计一个应用程序 (iOS),我正在尝试使用 UserDefaults (Swift 3,Xcode 8.3.3)。我之前添加了一些运行良好的键和值。
但是,当我添加更多密钥时,旧密钥仍然有效,但新密钥无效。具体来说,每当我尝试读取新密钥时,它们都会返回 0。
我已经搜索 Google 和 SO 很多年了,但仍然找不到我哪里出错了。
请帮忙!
在AppDelegate.swift
func applicationDidFinishLaunching(_ application: UIApplication) {
let d = UserDefaults.standard
let defaultValues = ["highScore" : 0,
"second" : 0,
"third" : 0,
"balls" : 0,
"maxLives" : 5,
"increaseML" : 250]
d.register(defaults: defaultValues)
}
在 MenuScene.swift(自定义 class)
var maxLives = defaults.integer(forKey: "maxLives")
var increaseML = defaults.integer(forKey: "increaseML")
出于某种原因,increaseML
和 maxLives
返回 0,即使我将它们的值分别设置为 250 和 5。
为什么会发生这种情况,我该如何解决?
我怀疑你的 applicationDidFinishLaunching
没有被调用。如果您使用 Storyboards
,可能是因为您的 Appdelegate
没有正确连接。
您可以按照此
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
每次启动应用程序时将调用什么。
此外,Apple 甚至不鼓励您在 this documentation 中使用 applicationDidFinishLaunching(_:)
。
令 d = UserDefaults.standard
let defaultValues = ["highScore" : 0,
"second" : 0,
"third" : 0,
"balls" : 0,
"maxLives" : 5,
"increaseML" : 250]
d.register(defaults: defaultValues)
d.synchronize()