Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults - should your app's key names be fully qualified?

I have an iOS app, and as usual I store the user's preferences in NSUserDefaults (or UserDefaults as it is now called in Swift).

let ud = UserDefaults.standard
let foo = 123
ud.set(foo, forKey: "foo")
ud.integer(forKey: "foo")

Should key names be long, to defend against conflicts with the system, or are you safe just thinking about your application's names?

let fooKey = "com.mycompany.myapp.foo"
// or...
let fooKey = "foo" 
like image 224
Rob N Avatar asked Sep 29 '16 18:09

Rob N


2 Answers

Your app's user defaults are only used by your app. However, your app may include lots of uses of user defaults. This can include your own code, code by 3rd parties, and Apple's frameworks.

To avoid any possibility of a key name collision, all third party code should certainly use fully qualified key names. I believe any keys added by Apple already does this.

As an app developer I at least prefix my keys with the name of my app to be safe. A fully qualified name is fine but probably isn't necessary.

I'd use "MyApp.foo".

like image 127
rmaddy Avatar answered Sep 21 '22 12:09

rmaddy


You are safe just thinking about your application's names, because your app is sandboxed and cannot actually access UserDefaults values belonging to other apps.

From the docs for NSUserDefaults:

A sandboxed app cannot access or modify the preferences for any other app. (For example, if you add another app's domain using the addSuiteNamed: method, you do not gain access to that app's preferences.)

Attempting to access or modify another app's preferences does not result in an error, but when you do, macOS actually reads and writes files located within your app's container, rather than the actual preference files for the other application.

https://developer.apple.com/reference/foundation/nsuserdefaults?language=objc

like image 42
charmingToad Avatar answered Sep 21 '22 12:09

charmingToad