Class

UserDefaults

An interface to the user's defaults database, where you store key-value pairs persistently across invocations of your app on a given device.

Overview

The UserDefaults 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.

At runtime, you use an UserDefaults object to read the defaults that your application uses from a user’s defaults database. UserDefaults 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 UserDefaults 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 UserDefaults 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 UserDefaults class does not currently support per-host preferences. To do this, you must use the CFPreferences API (see Preferences Utilities). However, UserDefaults correctly reads per-host preferences, so you can safely mix CFPreferences code with UserDefaults code.

If your application supports managed environments, you can use an UserDefaults 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.

You can use key-value observing to register observers for specific keys of interest in order to be notified of all updates to a local defaults database. For more details, see Key-Value Observing Programming Guide.

The UserDefaults 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 NSURL 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 set(_:forKey:). This allows you to call 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.

Storing Preferences in iCloud

An app can use the iCloud key-value store to share small amounts of data with other instances of itself on the user’s other computers and iOS devices. For example, a magazine app might store the current issue and page number being read by the user so that other instances of the app can open to the same page when launched.

For more information, see Storing Preferences in iCloud in Preferences and Settings Programming Guide.

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 addSuite(named:) 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.

Topics

Getting the Shared NSUserDefaults Instance

class var standard: UserDefaults

Returns the shared defaults object.

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 object(forKey: String)

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

func url(forKey: String)

Returns the NSURL instance associated with the specified key.

func array(forKey: String)

Returns the array associated with the specified key.

func dictionary(forKey: String)

Returns the dictionary object associated with the specified key.

func string(forKey: String)

Returns the string associated with the specified key.

func stringArray(forKey: String)

Returns the array of strings associated with the specified key.

func data(forKey: String)

Returns the data object associated with the specified key.

func bool(forKey: String)

Returns the Boolean value associated with the specified key.

func integer(forKey: String)

Returns the integer value associated with the specified key..

func float(forKey: String)

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

func double(forKey: String)

Returns the double value associated with the specified key.

func dictionaryRepresentation()

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

Setting Default Values

func set(Any?, forKey: String)

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

func set(URL?, forKey: String)

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

func set(Bool, forKey: String)

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

func set(Int, forKey: String)

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

func set(Float, forKey: String)

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

func set(Double, forKey: String)

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

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.

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 user defaults are changed within the current process.

class let sizeLimitExceededNotification: NSNotification.Name

This notification is posted when more data is stored in user defaults than is allowed.

class let completedInitialCloudSyncNotification: NSNotification.Name

This notification is posted when ubiquitous defaults finish downloading data, either the first time a device is connected to an iCloud account or when a user switches their primary iCloud account.

class let didChangeCloudAccountsNotification: NSNotification.Name

This notification is posted when the user changes the primary iCloud account.

class let noCloudAccountNotification: NSNotification.Name

This notification is posted when a cloud default is set, but no iCloud user is logged in.

Relationships

Inherits From

Conforms To