User Defaults is not registering new keys?

I'm designing an app (iOS) and I'm trying to use UserDefaults (Swift 3, Xcode 8.3.3). I had previously added some keys and values which were working fine.

However, when I added some more keys, the old keys were still working but the new keys were not working. Specifically, the new keys were returning 0 whenever I tried to read them.

I have searched Google and SO for ages and still can't find where I'm going wrong.

Please help!

In 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)

}

In MenuScene.swift (custom class)

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

For some reason, increaseML and maxLives are returning 0 even though I set their values to be 250 and 5 respectively.

Why is this happening and how can I fix this?

2 answers

  • answered 2017-08-12 09:42 dirtydanee

    I would suspect that your applicationDidFinishLaunching is not invoked. It could be caused, if you are using Storyboards, that your Appdelegate is not hooked up properly.

    You can fix it following this asnwer or move the initialisation of your defaults to:

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

    what will be called every time the application launches.

    Also, Apple even discourages you from using applicationDidFinishLaunching(_:) in this documentation.

  • answered 2017-08-12 18:30 Dev

    let d = UserDefaults.standard

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