Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults in iOS Playground

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?

like image 700
Daniel Avatar asked Jul 03 '15 15:07

Daniel


People also ask

What is NSUserDefaults in IOS?

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.

Where are the NSUserDefaults values stored?

The standard UserDefaults are stored in a property list document (. plist) in your app bundle.

How NSUserDefaults works?

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.

Is NSUserDefaults secure?

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.


1 Answers

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.

Example

The value becomes nil due to the fact that there's nothing to persist against.

like image 112
TheCodingArt Avatar answered Sep 19 '22 04:09

TheCodingArt