Class

UserDefaults

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an application to customize its behavior to match a user’s preferences. For example, you can allow users to determine what units of measurement your application displays or how often documents are automatically saved. Applications record such preferences by assigning values to a set of parameters in a user’s defaults database. The parameters are referred to as defaults since they’re commonly used to determine an application’s default state at startup or the way it acts by default.

Overview

At runtime, you use an NSUserDefaults object to read the defaults that your application uses from a user’s defaults database. NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. The synchronize() method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user’s defaults database.

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.

Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value. For example, if you set a mutable string as the value for "MyStringDefault", the string you later retrieve using string(forKey:) will be immutable.

A defaults database is created automatically for each user. The NSUserDefaults class does not currently support per-host preferences. To do this, you must use the CFPreferences API (see Preferences Utilities). However, NSUserDefaults correctly reads per-host preferences, so you can safely mix CFPreferences code with NSUserDefaults code.

If your application supports managed environments, you can use an NSUserDefaults object to determine which preferences are managed by an administrator for the benefit of the user. Managed environments correspond to computer labs or classrooms where an administrator or teacher may want to configure the systems in a particular way. In these situations, the teacher can establish a set of default preferences and force those preferences on users. If a preference is managed in this manner, applications should prevent users from editing that preference by disabling any appropriate controls.

The NSUserDefaults class is thread-safe.

Persistence of NSURL and file reference URLs

When using NSURL instances to refer to files within a process, it's important to make the distinction between location-based tracking (file: scheme URLs that are basically paths) versus filesystem identity tracking (file: scheme URLs that are file reference URLs). When persisting an NSURL, you should take that behavior into consideration. If your application tracks the resource being located by its identity so that it can be found if the user moves the file, then you should explicitly write the NSURL's bookmark data or encode a file reference URL.

If you want to track a file by reference but you require explicit control over when resolution occurs, you should take care to write out bookmark data to NSUserDefaults rather than rely on -[NSUserDefaults setURL:forKey:]. This allows you to call +[NSURL URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:] at a time when you know your application will be able to handle the potential I/O or required user interface interactions.

Sandbox Considerations

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.

Symbols

Getting the Shared NSUserDefaults Instance

class func resetStandardUserDefaults()

Synchronizes any changes made to the shared user defaults object and releases it from memory.

Initializing an NSUserDefaults Object

init()

Returns an NSUserDefaults object initialized with the defaults for the current user account.

init?(suiteName: String?)

Returns an NSUserDefaults object initialized with the defaults for the specified app group.

Registering Defaults

func register(defaults: [String : Any])

Adds the contents of the specified dictionary to the registration domain.

Getting Default Values

func array(forKey: String)

Returns the array associated with the specified key.

func bool(forKey: String)

Returns the Boolean value associated with the specified key.

func data(forKey: String)

Returns the data object associated with the specified key.

func dictionary(forKey: String)

Returns the dictionary object associated with the specified key.

func float(forKey: String)

Returns the floating-point value associated with the specified key.

func integer(forKey: String)

Returns the integer value associated with the specified key..

func object(forKey: String)

Returns the object associated with the first occurrence of the specified default.

func stringArray(forKey: String)

Returns the array of strings associated with the specified key.

func string(forKey: String)

Returns the string associated with the specified key.

func double(forKey: String)

Returns the double value associated with the specified key.

func url(forKey: String)

Returns the NSURL instance associated with the specified key.

Setting Default Values

func set(Bool, forKey: String)

Sets the value of the specified default key to the specified Boolean value.

func set(Float, forKey: String)

Sets the value of the specified default key to the specified floating-point value.

func set(Int, forKey: String)

Sets the value of the specified default key to the specified integer value.

func set(Any?, forKey: String)

Sets the value of the specified default key in the standard application domain.

func set(Double, forKey: String)

Sets the value of the specified default key to the double value.

func set(URL?, forKey: String)

Sets the value of the specified default key to the specified URL.

Removing Defaults

func removeObject(forKey: String)

Removes the value of the specified default key in the standard application domain.

Maintaining Persistent Domains

func synchronize()

Writes any modifications to the persistent domains to disk and updates all unmodified persistent domains to what is on disk.

func persistentDomain(forName: String)

Returns a dictionary containing the keys and values in the specified persistent domain.

func removePersistentDomain(forName: String)

Removes the contents of the specified persistent domain from the user’s defaults.

func setPersistentDomain([String : Any], forName: String)

Sets the dictionary for the specified persistent domain.

Accessing Managed Environment Keys

func objectIsForced(forKey: String)

Returns a Boolean value indicating whether the specified key is managed by an administrator.

func objectIsForced(forKey: String, inDomain: String)

Returns a Boolean value indicating whether the key in the specified domain is managed by an administrator.

Managing the Search List

func dictionaryRepresentation()

Returns a dictionary that contains a union of all key-value pairs in the domains in the search list.

Maintaining Volatile Domains

func removeVolatileDomain(forName: String)

Removes the specified volatile domain from the user’s defaults.

func setVolatileDomain([String : Any], forName: String)

Sets the dictionary for the specified volatile domain.

func volatileDomain(forName: String)

Returns the dictionary for the specified volatile domain.

var volatileDomainNames: [String]

The current volatile domain names.

Maintaining Suites

func addSuite(named: String)

Inserts the specified domain name into the receiver’s search list.

func removeSuite(named: String)

Removes the specified domain name from the receiver’s search list.

Constants

NSUserDefaults Domains

These constants specify various user defaults domains.

Notifications

class let didChangeNotification: NSNotification.Name

This notification is posted when a change is made to defaults in a persistent domain.

Relationships

Inherits From

Conforms To