macmade / user-defaults

Better NSUserDefaults

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Questions

kharmabum opened this issue · comments

(1) Every time a Preferences object is initialized the values in NSUserDefaults are set for each property's keypath, overriding any values that were set previously by the application.

(2) When the Preferences object is initialized the values of its properties are not set to the current values in NSUserDefaults.

Are (1) and (2) intended behavior?

The code uses a file to read defaults:

guard let path = Bundle.main.path( forResource: "Defaults", ofType: "plist" ) else

If you didn't add that resource, probably the init returns early.

Either you should add a plist resource, called Default.plist (can be empty), or remove line 39-44 (swift code).

Thank you for the comments guys. : )

@kharmabum is right, based on the blog article's code. I have just updated it, so it first read from the defaults before adding the observers.
This was of course not the intended behaviour. The code here was right, but I tried to keep the article as simple as possible, hence the unfortunate omission.

As @wdvr said, I use a Defaults.plist file to get default values.
This is not required, of course, but I find it easier this way.

@kharmabum if you take a look at the actual Swift code, you'll see:

for c in Mirror( reflecting: self ).children
{
    guard let key = c.label else
    {
        continue
    }
    
    self.setValue( UserDefaults.standard.object( forKey: key ), forKey: key )
    self.addObserver( self, forKeyPath: key, options: .new, context: nil )
}

See the self.setValue call, before adding the observer?
This will read from the user defaults, ensuring the instance is initialised with values from the suer defaults.

@macmade how the swift code is written now, it is required to have the Defaults.plist, otherwise the setValue and addObserver code you referred to will not be executed (will exit in the guard at line 41).

@wdvr Thanks for the pull request. This has been merged. : )

I think this can now be closed.