代码之家  ›  专栏  ›  技术社区  ›  Adi219

用户默认值不是注册新密钥?

  •  1
  • Adi219  · 技术社区  · 8 年前

    我在谷歌上搜索了很多年,但仍然找不到哪里出了问题。

    在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(自定义类)

    var maxLives = defaults.integer(forKey: "maxLives")
    var increaseML = defaults.integer(forKey: "increaseML")
    

    出于某种原因, increaseML maxLives 返回0,即使我将其值分别设置为250和5。

    为什么会发生这种情况?我该如何解决?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Community Mohan Dere    5 年前

    我怀疑你的 applicationDidFinishLaunching 未调用。如果您使用 Storyboards ,这是您的 Appdelegate 未正确连接。

    asnwer

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
    

    每次应用程序启动时都会调用什么。

    此外,苹果甚至不鼓励你使用 applicationDidFinishLaunching(_:) 在里面 this documentation

        2
  •  1
  •   Dev    8 年前

    设d=UserDefaults.standard

    let defaultValues = ["highScore"  : 0,
                         "second"     : 0,
                         "third"      : 0,
                         "balls"      : 0,
                         "maxLives"   : 5,
                         "increaseML" : 250]
    
    d.register(defaults: defaultValues)
    d.synchronize()