There seems to be a strange issue with iOS Playgrounds where NSUserDefaults
always returnsnil
instead of the actual value.
In an iOS Playground the last line wrongly returns nil
.
import UIKit
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("This is a test", forKey: "name")
let readString = defaults.objectForKey("name")
In an OSX Playground the last line correctly returns "This is a test".
import Cocoa
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("This is a test", forKey: "name")
let readString = defaults.objectForKey("name")
Any idea why this is? Bug?
Overview. The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user's preferences. For example, you can allow users to specify their preferred units of measurement or media playback speed.
The standard UserDefaults are stored in a property list document (. plist) in your app bundle.
A property list, or NSUserDefaults can store any type of object that can be converted to an NSData object. It would require any custom class to implement that capability, but if it does, that can be stored as an NSData. These are the only types that can be stored directly.
Because NSUserDefaults stores all data in an unencrypted . plist file, a curious person could potentially view this data with minimal effort. That means that you should never store any type of sensitive data inside NSUserDefaults.
That's not really a bug..... NSUserDefaults is tied to the iOS sandbox environment. Playgrounds doesn't run in this environment. Hence why you won't be able to write files to disk. If you run this code in the application when running via the simulator or device, you'll have access to the sandbox environment and NSUserDefaults will return a proper reference. I do see though that I get a proper reference in playgrounds and can set and get values, so there has to be something else going on here. I just wouldn't rely on this being the way to test this type of functionality due to the nature.
Notice what happens when I synchronize the store.
The value becomes nil due to the fact that there's nothing to persist against.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With