NSUserDefaults on iOS Playground

There seems to be a weird issue with iOS playgrounds, where NSUserDefaults always returns nil instead of the actual value.

On an iOS playground, the last line erroneously returns nil .

 import UIKit let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject("This is a test", forKey: "name") let readString = defaults.objectForKey("name") 

On 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? Mistake?

+8
ios xcode swift swift-playground nsuserdefaults
source share
4 answers

This is actually not a mistake ... NSUserDefaults is tied to the iOS sandbox environment. Playgrounds do not work in this environment. Therefore, you cannot write files to disk. If you run this code in the application when working with a simulator or device, you will have access to the sandbox environment, and NSUserDefaults will return the correct link. I see that I am getting the correct link on the playgrounds and can set and receive values, so there should be something else here. I simply would not rely on the fact that this is a way to test this type of functionality due to nature.

Note what happens when the storage is synchronized.

Example

The value becomes zero due to the fact that nothing remains with it.

+7
source share

For what it's worth, the following code works fine in iOS Playground version 1.6.1 (Swift 4):

 import Foundation let defaults = UserDefaults.standard defaults.set("This is a test", forKey: "name") let readString = defaults.string(forKey: "name") print(readString!) 

prints:

 This is a test 
+2
source share

The code works correctly in Xcode 6.4, but does not work in Xcode 7.0 beta (7A120f).

+1
source share

In Xcode 9.2 for iOS, it works even with UserDefaults persisting between repeats of the playground. This annoyed me at first because I expected UserDefaults to be cleaned up after each stop, as before. So, a warning: UserDefaults are now saved between repetitions, better remember this when searching for errors, there may be side effects!

0
source share

All Articles