7

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" 
Rob N
  • 15,024
  • 17
  • 92
  • 165
  • your app's user defaults are unique for your app, of course you can use a shared container for sharing data between e.g. extensions and the core app, but basically you don't need to keep the keys namespaced _explicticly_, it happens _implicitly_, anyway. – holex Sep 29 '16 at 18:51

2 Answers2

10

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".

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Okay, the 3rd party libraries explain why I see so many other values when I typed this in debugger: `p UserDefaults.standard.dictionaryRepresentation()`. – Rob N Sep 29 '16 at 18:56
  • A common way is also a format consisting of the application name combined with the option name without the proposed dot, in this case `MyAppFoo`. – Lukáš Kubánek Mar 03 '19 at 13:54
1

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

charmingToad
  • 1,597
  • 11
  • 18
  • At the same time, "Setting a default has no effect on the value returned by the `object(forKey:)` method if the same key exists in a domain that precedes the application domain in the search list." – zrslv Dec 28 '18 at 12:02