sunshinejr / SwiftyUserDefaults

Modern Swift API for NSUserDefaults
http://radex.io/swift/nsuserdefaults/static
MIT License
4.85k stars 366 forks source link

Keep Getting nil for String #158

Closed JeffreyBytes closed 6 years ago

JeffreyBytes commented 6 years ago

I have a file called Preferences.swift:

extension DefaultsKeys { static let bearerToken = DefaultsKey<String?>("bearerToken") }

I'm trying to show the default value in a Preferences window. bearerTokenTextField.stringValue = Defaults[.bearerToken] ?? ""

Where bearerTokenTextField is the text field I'm trying to display the information in.

I keep getting "Unexpectedly found nil while unwrapping"

I've also tried to use the Defaults["bearerToken"].stringValue and get the same error.

Any clue what I'm doing wrong?

sunshinejr commented 6 years ago

Hey @spaz926. What version of SwiftyUserDefaults your running?

JeffreyBytes commented 6 years ago

The current stable release. But I was also having the same issue on the 4.0 beta release as well.

sunshinejr commented 6 years ago

Hmm, couldn't really reproduce it, unfortunately... Would you be up for creating a sample project that has this error in it? It will be a lot easier to help you this way.

JeffreyBytes commented 6 years ago

I made a sample project... and it works as expected.

So something is going wrong in my project specifically and it is not an issue with SwiftyUserDefaults.

JeffreyBytes commented 6 years ago

Ok. So it seems the underlying issue is nothing is getting saved in ~/Library/Preferences

JeffreyBytes commented 6 years ago

Sorry for multiple replies, but I finally figured out what is causing the issue. My Preferences window contains a Tab View Controller. When the selected default tab is not the one I'm trying to show the preference on, it results in the nil value. I've uploaded a project showing this. Now I have to figure out how to get it to only attempt to show the default value in the text field when the correct tab is showing.

https://github.com/spaz926/SwiftyUserDefaultsExample

sunshinejr commented 6 years ago

Oh no worries at all @spaz926! Thanks for letting us know and hopefully you'll resolve your issue quickly 😉