Next Page > Hide TOC

Legacy Documentclose button

Important: The information in this document is obsolete and should not be used for new development.

NSUserDefaults

Inherits from
Package
com.apple.cocoa.foundation
Companion guide

Class at a Glance

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system.

Principal Attributes

Commonly Used Methods

objectForKey

Returns the default value for the specified key.

setObjectForKey

Sets the default value for the specified key.

removeObjectForKey

Removes the default entry identified by the specified key.

registerDefaults

Adds the specified defaults to the RegistrationDomain—a cache of application-provided defaults that are used unless a user overrides them.

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.

A defaults database is created automatically for each user.

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.

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.

A default’s value can be only property list objects: NSData, string, number, NSDate, NSArray, or NSDictionary.

!

Warning:  User defaults are not thread safe.

Tasks

Constructors

Getting the Shared Instance

Getting a Default

Setting and Removing Defaults

Accessing Managed Environment Keys

Setting and Getting the Search List

Maintaining Persistent Domains

Maintaining Volatile Domains

Registering Defaults

Maintaining Suites

Constructors

NSUserDefaults

Creates an NSUserDefaults for the current user account and with the argument and registration domains set up.

public NSUserDefaults()

Discussion

This constructor does not put anything in the search list.

See Also

Static Methods

resetStandardUserDefaults

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

public static void resetStandardUserDefaults()

Discussion

A subsequent invocation of standardUserDefaults creates a new shared user defaults object with the standard search list.

standardUserDefaults

Returns the shared defaults object.

public static NSUserDefaults standardUserDefaults()

Discussion

If it does not exist yet, it is created with a search list containing the names of the following domains, in this order:

The defaults are initialized for the current user. Subsequent modifications to the standard search list remain in effect even when this method is invoked again—the search list is guaranteed to be standard only the first time this method is invoked. The shared instance is provided as a convenience.

Instance Methods

addSuiteNamed

Inserts a new domain, suiteName, into the receiver’s search list.

public void addSuiteNamed(String suiteName)

Discussion

The suite domain is inserted after the application domain.

The suiteName domain is similar to a bundle identifier string, but is not tied to a particular application or bundle. A suite can be used to hold preferences that are shared between multiple applications.

See Also

arrayForKey

Invokes objectForKey with key defaultName.

public NSArray arrayForKey(String defaultName)

Discussion

Returns the value associated with defaultName if it’s an NSArray object and null otherwise.

See Also

booleanForKey

Invokes stringForKey with key defaultName.

public boolean booleanForKey(String defaultName)

Discussion

Returns true if the value associated with defaultName is an String containing the word “yes” in uppercase or lowercase or responds to the intValue message by returning a nonzero value. Otherwise, returns false.

See Also

dataForKey

Invokes objectForKey with key defaultName.

public NSData dataForKey(String defaultName)

Discussion

Returns the corresponding value if it’s an NSData object and null otherwise.

See Also

dictionaryForKey

Invokes objectForKey with key defaultName.

public NSDictionary dictionaryForKey(String defaultName)

Discussion

Returns the corresponding value if it’s an NSDictionary object and null otherwise.

See Also

dictionaryRepresentation

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

public NSDictionary dictionaryRepresentation()

Discussion

As with objectForKey, key-value pairs in domains that are earlier in the search list take precedence. The combined result doesn’t preserve information about which domain each entry came from.

See Also

doubleForKey

Invokes stringForKey with key defaultName.

public double doubleForKey(String defaultName)

Discussion

Returns 0 if no string is returned. Otherwise, the resulting string is sent a doubleValue message, which provides this method’s return value.

See Also

floatForKey

Invokes stringForKey with key defaultName.

public float floatForKey(String defaultName)

Discussion

Returns 0 if no string is returned. Otherwise, the resulting string is sent a floatValue message, which provides this method’s return value.

See Also

integerForKey

Invokes stringForKey with key defaultName.

public int integerForKey(String defaultName)

Discussion

Returns 0 if no string is returned. Otherwise, the resulting string is sent an intValue message, which provides this method’s return value.

See Also

longForKey

Invokes stringForKey with key defaultName.

public long longForKey(String defaultName)

Discussion

Returns 0 if no string is returned. Otherwise, the resulting string is sent a longValue message, which provides this method’s return value.

See Also

objectForKey

Returns the value of the first occurrence of the default identified by defaultName, searching the domains included in the search list in the order they’re listed.

public Object objectForKey(String defaultName)

Discussion

Returns null if the default isn’t found.

See Also

objectForKeyInDomain

Returns the value for defaultName in the domain domainName.

public Object objectForKeyInDomain(String defaultName, String domainName)

Discussion

Only the defaults defined in the domainName for the current user for any host are searched. If defaultName is not found, null is returned.

See Also

objectIsForcedForKey

Determines whether key is managed by an administrator.

public boolean objectIsForcedForKey(String key)

Discussion

Returns true if the value of key is managed by an administrator; otherwise returns false. This method assumes that key is a preference associated with the current user and application. For managed keys, the application should disable any user interface that allows the user to modify the value of key.

Availability
See Also

objectIsForcedForKeyInDomain

Determines whether key is managed by an administrator.

public boolean objectIsForcedForKeyInDomain(String key, String domain)

Discussion

Returns true if the value of key in the specified domain is managed by an administrator; otherwise returns false. This method assumes that key is a preference associated with the current user. For managed keys, the application should disable any user interface that allows the user to modify the value of key.

Availability
See Also

persistentDomainForName

Returns a dictionary representing the persistent domain identified by domainName.

public NSDictionary persistentDomainForName(String domainName)

Discussion

The keys in the dictionary are names of defaults, and the value corresponding to each key is a property list object (NSData, String, Number, NSDate, NSArray, or NSDictionary). domainName should be your application’s bundle identifier.

See Also

persistentDomainNames

Returns an array containing the names of the current persistent domains.

public NSArray persistentDomainNames()

Discussion

You can get each domain by using the domain names in the array as arguments to persistentDomainForName.

See Also

registerDefaults

Adds the contents of dictionary to the registration domain.

public void registerDefaults(NSDictionary dictionary)

Discussion

If there is no registration domain, it’s created using dictionary, and RegistrationDomain is added to the end of the search list.

removeObjectForKey

Removes the value for the default identified by defaultName in the standard application domain.

public void removeObjectForKey(String defaultName)

Discussion

Removing a default has no effect on the value returned by the objectForKey method if the same key exists in a domain that precedes the standard application domain in the search list.

See Also

removeObjectForKeyInDomain

Deletes defaultName from the domain domainName for the current user on any host.

public void removeObjectForKeyInDomain(String defaultName, String domainName)

Discussion

If domainName is part of the receiver’s search list, posts an UserDefaultsDidChangeNotification.

See Also

removePersistentDomainForName

Removes the persistent domain identified by domainName from the user’s defaults.

public void removePersistentDomainForName(String domainName)

Discussion

The first time a persistent domain is changed after synchronize, a UserDefaultsDidChangeNotification is posted. domainName should be your application’s bundle identifier.

See Also

removeSuiteNamed

Removes the suiteName domain from the receiver’s search list.

public void removeSuiteNamed(String suiteName)

See Also

removeVolatileDomainForName

Removes the volatile domain identified by domainName from the user’s defaults.

public void removeVolatileDomainForName(String domainName)

See Also

searchList

This method has been deprecated.

public NSArray searchList()

See Also

setBooleanForKey

Sets the value of the default identified by defaultName to a string representation of true or false, depending on value.

public void setBooleanForKey(boolean value, String defaultName)

Discussion

Invokes setObjectForKey as part of its implementation.

See Also

setDoubleForKey

Sets the value of the default identified by defaultName to a string representation of value.

public void setDoubleForKey(double value, String defaultName)

Discussion

Invokes setObjectForKey as part of its implementation.

See Also

setFloatForKey

Sets the value of the default identified by defaultName to a string representation of value.

public void setFloatForKey(float value, String defaultName)

Discussion

Invokes setObjectForKey as part of its implementation.

See Also

setIntegerForKey

Sets the value of the default identified by defaultName to a string representation of value.

public void setIntegerForKey(int value, String defaultName)

Discussion

Invokes setObjectForKey as part of its implementation.

See Also

setLongForKey

Sets the value of the default identified by defaultName to a string representation of value.

public void setLongForKey(long value, String defaultName)

Discussion

Invokes setObjectForKey as part of its implementation.

See Also

setObjectForKey

Sets the value of the default identified by defaultName in the standard application domain.

public void setObjectForKey(Object value, String defaultName)

Discussion

Setting a default has no effect on the value returned by the objectForKey method if the same key exists in a domain that precedes the application domain in the search list.

See Also

setObjectForKeyInDomain

Sets value as the value for defaultName in the domain domainName for the current user on any host.

public void setObjectForKeyInDomain(Object value, String defaultName, String domainName)

Discussion

If domainName is part of the receiver’s search list, it posts an UserDefaultsDidChangeNotification.

See Also

setPersistentDomainForName

Sets the dictionary to domain for the persistent domain named domainName.

public void setPersistentDomainForName(NSDictionary domain, String domainName)

Discussion

The first time a persistent domain is changed after synchronize, a UserDefaultsDidChangeNotification is posted. domainName should be your application’s bundle identifier.

See Also

setSearchList

This method has been deprecated.

public void setSearchList(NSArray array)

See Also

setVolatileDomainForName

Sets the dictionary for the volatile domain named domainName to domain.

public void setVolatileDomainForName(NSDictionary domain, String domainName)

Discussion

This method throws an InvalidArgumentException if a volatile domain with domainName already exists.

See Also

stringForKey

Invokes objectForKey with key defaultName.

public String stringForKey(String defaultName)

Discussion

Returns the corresponding value if it’s a String object and null otherwise.

See Also

synchronize

Saves any modifications to the persistent domains and updates all persistent domains that were not modified to what is on disk.

public boolean synchronize()

Discussion

Returns false if it could not save data to disk. Because synchronize is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update user defaults to what is on disk even though you have not made any changes.

See Also

volatileDomainForName

Returns a dictionary representing the volatile domain identified by domainName.

public NSDictionary volatileDomainForName(String domainName)

Discussion

The keys in the dictionary are names of defaults, and the value corresponding to each key is a property list object (NSData, String, Number, NSDate, NSArray, or NSDictionary).

See Also

volatileDomainNames

Returns an array containing the names of the current volatile domains.

public NSArray volatileDomainNames()

Discussion

You can get each domain by using the domain names in the array as arguments to volatileDomainForName.

See Also

Constants

NSUserDefaults provides the following constants as a convenience. They provide access to values of the keys to the locale dictionary, which is discussed in “User Defaults”.

Constant

Description

AMPMDesignation

An array of strings that specify how the morning and afternoon designations are printed. The defaults are AM and PM.

CurrencySymbol

A string that specifies the symbol used to denote currency in this language. The default is “$”.

DateFormatString

A format string that specifies how dates are printed using the date format specifiers. The default is to use weekday names with full month names and full years, as in “Saturday, March 24, 2001.”

DateTimeOrdering

A string that specifies how to use ambiguous numbers in date strings. Specify this value as a permutation of the letters M (month), D (day), Y (year), and H (hour). For example, MDYH treats “2/3/01 10” as the 3rd day of February 2001 at 10:00 am, whereas DMYH treats the same value as the 2nd day of March 2001 at 10:00 am. If fewer numbers are specified than are needed, the numbers are prioritized to satisfy day first, then month, and then year. For example, if you supply only the value 12, it means the 12th day of this month in this year because the day must be specified. If you supply “2 12” it means either February 12 or December 2, depending on if the ordering is “MDYH” or “DMYH.”

DecimalDigits

Strings that identify the decimal digits in addition to or instead of the ASCII digits.

DecimalSeparator

A string that specifies the decimal separator. The decimal separator separates the ones place from the tenths place. The default is “.”.

EarlierTimeDesignations

An array of strings that denote a time in the past. These are adjectives that modify values from YearMonthWeekDesignations. The defaults are “prior,” “last,” “past,” and “ago.”

HourNameDesignations

Strings that identify the time of day. These strings should be bound to an hour. The default is this array of arrays: (0, midnight), (10, morning), (12, noon, lunch), (14, afternoon), (19, dinner).

InternationalCurrencyString

A string containing a three-letter abbreviation for currency, following the ISO 4217 standard.

LaterTimeDesignations

An array of strings that denotes a time in the future. This array is an adjective that modifies a value from YearMonthWeekDesignations. The default is (next).

MonthNameArray

An array that specifies the full names for the months.

NegativeCurrencyFormatString

A format string that specifies how negative numbers are printed when representing a currency value. The default is “–$9,999.00”.

NextDayDesignations

A string that identifies the day after today. The default is (tomorrow).

NextNextDayDesignations

A string that identifies the day after tomorrow. The default is (nextday).

PositiveCurrencyFormatString

A format string that specifies how positive numbers are printed when representing a currency value. The default is “$9,999.00”.

PriorDayDesignations

A string that identifies the day before today. The default is (yesterday).

ShortDateFormatString

A format string that specifies how dates are abbreviated. The default is to separate the day month and year with slashes and to put the day first, as in 31/10/01.

ShortMonthNameArray

An array that specifies the abbreviations for the months.

ShortTimeDateFormatString

A format string that specifies how times and dates are abbreviated. The default is to use dashes to separate the day, month, and year and to use a 12-hour clock, as in “31-Jan-01 1:30 PM. “

ShortWeekDayNameArray

An array that specifies the abbreviations for the days of the week. Sunday should be the first day of the week.

ThisDayDesignations

A string that identifies what this day is called. The default is (today, now).

ThousandsSeparator

A string that specifies the separator character for the thousands place of a decimal number. The default is a comma.

TimeDateFormatString

A format string that specifies how dates with times are printed. The default is to use full month names and days with a 24-hour clock, as in “Sunday, January 01, 2001 23:00:00 Pacific Standard Time.”

TimeFormatString

A format string that specifies how dates with times are printed. The default is to use a 12-hour clock.

WeekDayNameArray

An array that gives the names for the days of the week. Sunday should be the first day of the week.

YearMonthWeekDesignations

An array of strings that specifies the words for year, month, and week in the current locale. The defaults are “year,” “month,” and “week.”

Notifications

UserDefaultsDidChangeNotification

This notification is posted the first time after a synchronize when a change is made to defaults in a persistent domain.

The notification object is the NSUserDefaults instance. This notification does not contain a userInfo dictionary.



Next Page > Hide TOC


© 1997, 2006 Apple Computer, Inc. All Rights Reserved. (Last updated: 2006-07-24)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.