PATH  Documentation > Mac OS X > Foundation Reference: Java



Table of Contents

NSUserDefaults


Inherits from:
NSObject
Package:
com.apple.yellow.foundation

Class at a Glance


The NSUserDefaults class provides an 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.


Class Description


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 run time, 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.

WARNING

User defaults are not thread safe.


Domains


Defaults are grouped in domains. For example, there's a domain for application-specific defaults and another for system-wide defaults that apply to all applications.

All defaults are stored and accessed per user. Defaults that affect all users are not provided for.

Each domain has a name by which it's identified and stores defaults as key-value pairs in an NSDictionary object. Each default is made up of three components:

A domain is either persistent or volatile. Persistent domains are permanent and last past the life of the NSUserDefaults object. Persistent domains are stored in a user's defaults database. If you use NSUserDefaults to make a changes to a default in a persistent domain, the changes are saved in the user's defaults database automatically. On the other hand, volatile domains last only as long as the NSUserDefaults object exists; they aren't saved in the user's defaults database. The standard domains are:


Domain State
ArgumentDomain volatile
Application (Identified by the application's name) persistent
GlobalDomain persistent
Languages (Identified by the language names) volatile
RegistrationDomain volatile

A search for the value of a given default proceeds through the domains in an NSUserDefaults object's search list. Only domains in the search list are searched. The standard search list contains the domains from the table above, in the order listed. A search ends when the default is found. Thus, if multiple domains contain the same default, only the domain nearest the beginning of the search list provides the default's value. Using the setSearchList method, you can reorder the default search list or set up one that is a subset of all the user's domains.

The following sections describe the purpose of each of the domains.


ArgumentDomain


Default values can be set from command line arguments (if you start the application from the command line) as well as from a user's defaults database. Default values set from the command line go in the ArgumentDomain. They are set on the command line by preceding the default name with a hyphen and following it with a value. For example, the following command launches Project Builder and sets Project Builder's IndexOnOpen default to false:

localhost> ProjectBuilder.app/ProjectBuilder -IndexOnOpen NO

Defaults set from the command line temporarily override values from a user's defaults database. In the example above, Project Builder won't automatically index projects even if the user's IndexOnOpen preference is set to true in the defaults database.


Application Domain


The application domain contains application-specific defaults that are read from a user's defaults database. The application domain is identified by the bundle identifier of the application.


GlobalDomain


The global domain contains defaults that are read from a user's defaults database and are applicable to all applications that a user runs. Many Application Kit and Foundation objects use default values from the GlobalDomain. For example, NSRulerView objects automatically use a user's preferred measurement units, as stored in the user's defaults database under the key "MeasurementUnit." Consequently, ruler views in all applications use the user's preferred measurement units-unless an application overrides the default by creating an MeasurementUnit default in its application domain. Another GlobalDomain default, Languages, allows users to specify a preference of languages. For example, a user could specify English as the preferred language, followed by Spanish, French, German, Italian, and Swedish.


Languages


If a user has a value for the Languages default, then NSUserDefaults records language-specific default values in domains identified by the language name. The language specific domains contain defaults for a locale. Certain classes from the Foundation Framework (NSGregorianDate, NSDate, and NSTimeZone, for example) use locale defaults to modify their behavior. For example, when you request an String representation of an NSGregorianDate, the NSGregorianDate looks at the locale to determine what the months and the days of the week are named in your preferred language.


RegistrationDomain


The registration domain is a set of application-provided defaults that are used unless a user overrides them. For example, the first time you run Project Builder, there isn't an IndexOnOpen value saved in your defaults database. Consequently, Project Builder registers a default value for IndexOnOpen in the RegistrationDomain as a "catch all" value. Project Builder can thereafter assume that an NSUserDefaults object always has a value to return for the default, simplifying the use of user defaults.

You set RegistrationDomain defaults programmatically with the method registerDefaults.


Synchronizing an NSUserDefaults Object with the Defaults Database


Since other applications (and the user) can write to a defaults database, the database and an NSUserDefaults object might not agree on the value of a given default at all times. Using the synchronize method, you can update the defaults database with an NSUserDefaults object's new values and update the NSUserDefaults object with any changes that have been made to the database. In applications in which a run-loop is present, synchronize is automatically invoked at periodic intervals. Consequently, you might synchronize before exiting a process, but otherwise you shouldn't need to.


Using NSUserDefaults


Typically, you use this class by invoking the standardUserDefaults class method to get an NSUserDefaults object. This method returns a global NSUserDefaults object with a search list already initialized. Use the objectForKey and setObjectForKey methods to get and set default values.

For example, suppose that your application needs a default that specifies whether or not to delete backup files. You could use an NSUserDefaults object to manage your default, as follows:


Set a default in the NSRegistrationDomain


An application can set values for all its defaults in the RegistrationDomain. If users specify a different preference in their defaults database, the users' preferences override the values from the RegistrationDomain. An NSUserDefaults object only uses values from the RegistrationDomain when a user hasn't specified a different preference. So, you need to decide whether or not your application should delete backup files by default.

To register the application's default behavior, you get the application's shared instance of NSUserDefaults and register default values with it. A good place to do this is in the initialize method of the class that uses the default.

The initialize message is sent to each class before it receives any other message, ensuring that the application's defaults are set before the application needs to read them.


Allow the user to specify a different default behavior


To allow users to specify a different default behavior for deleting backups, you must provide an interface in which they can express their preference. Most applications provide a Preferences panel for this purpose. When your application detects that a user has specified a new preference, it should save it in the shared instance of NSUserDefaults.

For example, assume that your application has an instance variable called deleteBackupButton that is an outlet to an NSButton, and that users toggle this button's state to indicate whether or not the application should delete its backup files.

After determining the button's state, setObjectForKey is used to set the value of the specified default in the application domain.

You don't have to use a Preferences panel to manage all defaults. For example, an NSWindow can store its placement in the user defaults system, so that it appears in the same location the next time the user starts the application.


Use the default value to determine behavior


As a convenience, NSUserDefaults provides booleanForKey, floatForKey, and so on. Recall that a default's value can be only an NSData, String, NSArray, or NSDictionary. booleanForKey and similarly named methods attempt to get the value for the specified default and interpret it as a different data type.




Constants


NSUserDefaults provides the following constants as a convenience. They provide access to values of the keys to the locale dictionary, which was discussed earlier in "Languages" .


Constant Type Key Name and Description
AMPMDesignation String An array of strings that specify how the morning and afternoon designations are printed. The default is AM and PM.
CurrencySymbol String A string that specifies the symbol used to denote currency in this language. The default is "$".
DateFormatString String 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 "Sunday, January 01, 1995."
DateTimeOrdering String 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/95 10" as the 3rd day of February 1995 at 10:00am, whereas DMYH treats the same value as the 2nd day of March 1995 at 10:00am. If fewer numbers are specified than are needed, the numbers are prioritized to satisfy day first, then the month, and then the 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 String Strings that identify the decimal digits in addition to or instead of the ASCII digits.
DecimalSeparator String A string that specifies the decimal separator. The decimal separator separates the ones place from the tenths place. The default is ".".
EarlierTimeDesignations String An array of strings that denote a time in the past. These are adjectives that modify values from NSYearMonthWeekDesignations. The defaults are "prior," "last," "past," and "ago."
HourNameDesignations String Strings that identify the time of day. These strings should be bound to an hour. The default is this array of arrays: (0, midnight), (12, noon, lunch), (10, morning), (14, afternoon), (19, dinner).
InternationalCurrencyString String A string containing three letter abbreviation for currency, following the ISO 4217 standard.
LaterTimeDesignations String An array of strings that denote a time in the future. This is an adjective that modifies a value from YearMonthWeekDesignations. The default is "next.".
MonthNameArray String An array that specifies the full names for the months.
NegativeCurrencyFormatString String
NextDayDesignations String A string that identifies the day after today. The default is "tomorrow."
NextNextDayDesignations String A string that identifies the day after tomorrow. The default is "nextday".
PositiveCurrencyFormatString String
PriorDayDesignations String A string that identifies the day before today. The default is "yesterday."
ShortDateFormatString String 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/95.
ShortMonthNameArray String An array that specifies the abbreviations for the months.
ShortTimeDateFormatString String 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-95 1:30 PM.
ShortWeekDayNameArray String An array that specifies the abbreviations for the days of the week. Sunday should be the first day of the week.
ThisDayDesignations String A string that identifies what this day is called. The default is "today."
ThousandsSeparator String A string that specifier the separator character for the thousands place of a decimal number. The default is a comma.
TimeDateFormatString String A format string how dates with times are printed. The default is to use abbreviated months and days with a 24 hour clock, as in "Sun Jan 01 23:00:00 +6 2001."
TimeFormatString String A format string how dates with times are printed. The default is to use a 24 hour clock, as in 13:30:25.
WeekDayNameArray String An array that gives the names for the days of the week. Sunday should be the first day of the week.
YearMonthWeekDesignations String An array of strings that specify the word for year, month, and week in the current locale. The defaults are "year," "month," and "week."



Method Types


Constructors
NSUserDefaults
Getting the shared instance
standardUserDefaults
resetStandardUserDefaults
Getting a default
arrayForKey
booleanForKey
dataForKey
dictionaryForKey
doubleForKey
floatForKey
integerForKey
longForKey
objectForKey
objectForKeyInDomain
stringForKey
Setting and removing defaults
removeObjectForKey
removeObjectForKeyInDomain
setBooleanForKey
setDoubleForKey
setFloatForKey
setIntegerForKey
setLongForKey
setObjectForKey
setObjectForKeyInDomain
Setting and getting the search list
setSearchList
searchList
dictionaryRepresentation
Maintaining persistent domains
persistentDomainForName
persistentDomainNames
removePersistentDomainForName
setPersistentDomainForName
synchronize
Maintaining volatile domains
removeVolatileDomainForName
setVolatileDomainForName
volatileDomainForName
volatileDomainNames
Registering defaults
registerDefaults


Constructors



NSUserDefaults

public NSUserDefaults()

Description forthcoming.


Static Methods



resetStandardUserDefaults

public static void resetStandardUserDefaults()

Description forthcoming.

standardUserDefaults

public static NSUserDefaults standardUserDefaults()

Returns the shared defaults object. If it doesn't exist yet, it's 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



arrayForKey

public NSArray arrayForKey(String defaultName)

Invokes objectForKey with key defaultName. Returns the value associated with defaultName if it's an NSArray object and null otherwise.

See Also: booleanForKey, dataForKey, dictionaryForKey, doubleForKey, floatForKey, integerForKey, longForKey, objectForKey, stringForKey



booleanForKey

public boolean booleanForKey(String defaultName)

Invokes stringForKey: with key defaultName. Returns true if the value associated with defaultName is an String containing uppercase or lowercase "YES" or responds to the intValue message by returning a non-zero value. Otherwise, returns false.

See Also: arrayForKey, dataForKey, dictionaryForKey , doubleForKey, floatForKey, integerForKey, longForKey, objectForKey, stringForKey



dataForKey

public NSData dataForKey(String defaultName)

Invokes objectForKey with key defaultName. Returns the corresponding value if it's an NSData object and null otherwise.

See Also: arrayForKey, booleanForKey, dictionaryForKey, doubleForKey, floatForKey, integerForKey, longForKey, objectForKey, stringForKey



dictionaryForKey

public NSDictionary dictionaryForKey(String defaultName)

Invokes objectForKey with key defaultName. Returns the corresponding value if it's an NSDictionary object and null otherwise.

See Also: arrayForKey, booleanForKey, dataForKey, doubleForKey, floatForKey, integerForKey, longForKey, objectForKey, stringForKey



dictionaryRepresentation

public NSDictionary dictionaryRepresentation()

Returns a dictionary that contains a union of all key-value pairs in the domains in the search list. 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: searchList



doubleForKey

public double doubleForKey(String defaultName)

Invokes stringForKey with key defaultName. 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: arrayForKey, booleanForKey, dataForKey, dictionaryForKey, integerForKey, floatForKey, longForKey, objectForKey, stringForKey



floatForKey

public float floatForKey(String defaultName)

Invokes stringForKey with key defaultName. 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: arrayForKey, booleanForKey, dataForKey, dictionaryForKey, doubleForKey, integerForKey, longForKey, objectForKey, stringForKey



integerForKey

public int integerForKey(String defaultName)

Invokes stringForKey with key defaultName. 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: arrayForKey, booleanForKey, dataForKey, doubleForKey, dictionaryForKey, floatForKey, longForKey, objectForKey, stringForKey



longForKey

public long longForKey(String defaultName)

Invokes stringForKey with key defaultName. Returns 0 if no string is returned. Otherwise, the resulting string is sent an longValue message, which provides this method's return value.

See Also: arrayForKey, booleanForKey, dataForKey, doubleForKey, dictionaryForKey, floatForKey, integerForKey, objectForKey, stringForKey



objectForKey

public Object objectForKey(String defaultName)

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. Returns null if the default isn't found.

See Also: arrayForKey, booleanForKey, dataForKey, dictionaryForKey, doubleForKey, floatForKey, longForKey, , stringForKey



objectForKeyInDomain

public Object objectForKeyInDomain( String aString, String domainName)

Description forthcoming.

persistentDomainForName

public NSDictionary persistentDomainForName(String domainName)

Returns a dictionary representing the persistent domain identified by domainName. The keys in the dictionary are names of defaults, and the value corresponding to each key is a property-list object (String, NSDictionary, NSArray, or NSData). domainName should be your application's bundle identifier.

See Also: removePersistentDomainForName, setPersistentDomainForName



persistentDomainNames

public NSArray persistentDomainNames()

Returns an array containing the names of the current persistent domains. You can get each domain by using the domain names in the array as arguments to persistentDomainForName.

See Also: removePersistentDomainForName, setPersistentDomainForName



registerDefaults

public void registerDefaults(NSDictionary dictionary)

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

removeObjectForKey

public void removeObjectForKey(String defaultName)

Removes the value for the default identified by defaultName in the standard application domain. 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: setObjectForKey



removeObjectForKeyInDomain

public void removeObjectForKeyInDomain( String aString, String domainName)

Description forthcoming.

removePersistentDomainForName

public void removePersistentDomainForName(String domainName)

Removes the persistent domain identified by domainName from the user's defaults. The first time a persistent domain is changed after synchronize, a UserDefaultsChanged notification is posted. domainName should be your application's bundle identifier.

See Also: setPersistentDomainForName



removeVolatileDomainForName

public void removeVolatileDomainForName(String domainName)

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

See Also: setVolatileDomainForName



searchList

public NSArray searchList()

Returns an array of domain names, identifying the domains objectForKey will search.

See Also: setSearchList, dictionaryRepresentation



setBooleanForKey

public void setBooleanForKey( boolean value, String defaultName)

Sets the value of the default identified by defaultName to a string representation of true or false, depending on value. Invokes setObjectForKey as part of its implementation.

See Also: booleanForKey



setDoubleForKey

public void setDoubleForKey( double value, String defaultName)

Sets the value of the default identified by defaultName to a string representation of value. Invokes setObjectForKey as part of its implementation.

See Also: doubleForKey



setFloatForKey

public void setFloatForKey( float value, String defaultName)

Sets the value of the default identified by defaultName to a string representation of value. Invokes setObjectForKey as part of its implementation.

See Also: floatForKey



setIntegerForKey

public void setIntegerForKey( int value, String defaultName)

Sets the value of the default identified by defaultName to a string representation of value. Invokes setObjectForKey as part of its implementation.

See Also: integerForKey



setLongForKey

public void setLongForKey( long value, String defaultName)

Sets the value of the default identified by defaultName to a string representation of value. Invokes setObjectForKey as part of its implementation.

See Also: longForKey



setObjectForKey

public void setObjectForKey( Object value, String defaultName)

Sets the value of the default identified by defaultName in the standard application domain. 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: removeObjectForKey



setObjectForKeyInDomain

public void setObjectForKeyInDomain( Object anObject, String domainName)

Description forthcoming.

setPersistentDomainForName

public void setPersistentDomainForName( NSDictionary domain, String domainName)

Sets the dictionary for the persistent domain named domainName-throws an InvalidArgumentException if a persistent domain with domainName already exists. The first time a persistent domain is changed after synchronize, an UserDefaultsChanged notification is posted. domainName should be your application's bundle identifier.

See Also: persistentDomainForName, persistentDomainNames



setSearchList

public void setSearchList(NSArray array)

Sets the domains objectForKey: will search. Domain names in array with no corresponding user default domain are ignored.

See Also: searchList



setVolatileDomainForName

public void setVolatileDomainForName( NSDictionary domain, String domainName)

Sets the dictionary for the volatile domain named domainName to domain. This method throws an InvalidArgumentException if a volatile domain with domainName already exists.

See Also: volatileDomainForName, volatileDomainNames



stringForKey

public String stringForKey(String defaultName)

Invokes objectForKey: with key defaultName. Returns the corresponding value if it's a String object and null otherwise.

See Also: arrayForKey, booleanForKey, dataForKey, dictionaryForKey, doubleForKey, floatForKey, integerForKey, longForKey, objectForKey



synchronize

public boolean synchronize()

Saves any modifications to the persistent domains and updates all persistent domains that were not modified to what is on disk. 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: persistentDomainForName, persistentDomainNames, removePersistentDomainForName, setPersistentDomainForName



volatileDomainForName

public NSDictionary volatileDomainForName(String domainName)

Returns a dictionary representing the volatile domain identified by domainName. The keys in the dictionary are names of defaults, and the value corresponding to each key is a property-list object (String, NSData, NSDictionary, NSArray).

See Also: removeVolatileDomainForName, setVolatileDomainForName



volatileDomainNames

public NSArray volatileDomainNames()

Returns an array containing the names of the current volatile domains. You can get each domain by using the domain names in the array as arguments to volatileDomainForName.

See Also: removeVolatileDomainForName, setVolatileDomainForName




Notifications


UserDefaultsDidChangeNotification

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

This notification contains a notification object but no userInfo dictionary. The notification object is the NSUserDefaults instance.



Table of Contents