Class

NSUserDefaults

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

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 stringForKey: 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.

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 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 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 setURL: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 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.

Topics

Getting the Shared NSUserDefaults Instance

standardUserDefaults

Returns the shared defaults object.

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.

initWithUser:

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

Deprecated
initWithSuiteName:

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

Registering Defaults

registerDefaults:

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

Getting Default Values

objectForKey:

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

URLForKey:

Returns the NSURL instance associated with the specified key.

arrayForKey:

Returns the array associated with the specified key.

dictionaryForKey:

Returns the dictionary object associated with the specified key.

stringForKey:

Returns the string associated with the specified key.

stringArrayForKey:

Returns the array of strings associated with the specified key.

dataForKey:

Returns the data object associated with the specified key.

boolForKey:

Returns the Boolean value associated with the specified key.

integerForKey:

Returns the integer value associated with the specified key..

floatForKey:

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

doubleForKey:

Returns the double value associated with the specified key.

dictionaryRepresentation

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

Setting Default Values

setObject:forKey:

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

setURL:forKey:

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

setBool:forKey:

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

setInteger:forKey:

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

setFloat:forKey:

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

setDouble:forKey:

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

Removing Defaults

removeObjectForKey:

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

Maintaining Persistent Domains

synchronize

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

persistentDomainForName:

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

persistentDomainNames

Returns an array of the current persistent domain names.

Deprecated
removePersistentDomainForName:

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

setPersistentDomain:forName:

Sets the dictionary for the specified persistent domain.

Accessing Managed Environment Keys

objectIsForcedForKey:

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

objectIsForcedForKey:inDomain:

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

Maintaining Volatile Domains

removeVolatileDomainForName:

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

setVolatileDomain:forName:

Sets the dictionary for the specified volatile domain.

volatileDomainForName:

Returns the dictionary for the specified volatile domain.

volatileDomainNames

The current volatile domain names.

Maintaining Suites

addSuiteNamed:

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

removeSuiteNamed:

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

Constants

NSUserDefaults Domains

These constants specify various user defaults domains.

Language-Dependent Date/Time Information

The NSUserDefaults class provides the following constants as a convenience. They provide access to values of the keys to the locale dictionary, which is discussed in Preferences and Settings Programming Guide.

Language-Dependent Numeric Information

The NSUserDefaults class provides the following constants as a convenience. They provide access to values of the keys to the locale dictionary, which is discussed in Preferences and Settings Programming Guide.

Notifications

NSUserDefaultsDidChangeNotification

This notification is posted when user defaults are changed within the current process.

NSUserDefaultsSizeLimitExceededNotification

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

NSUbiquitousUserDefaultsCompletedInitialSyncNotification

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.

NSUbiquitousUserDefaultsDidChangeAccountsNotification

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

NSUbiquitousUserDefaultsNoCloudAccountNotification

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

Relationships

Inherits From