The Nsuserdefaults class provides a programmatic interface for interacting with the default system. The Nsuserdefaults object is used to save, restore application-related preferences, configuration data, and so on . The default system allows the application to customize its behavior to suit the user's preferences. You can read the program's settings from the user's default database while the program is running. At the same time, the nsuserdefaults cache avoids the operation of opening the user's default database every time the data is read. You can synchronize the in-memory cache with the user's default system by calling the Synchronize method.
The Nsuserdefaults class provides a very convenient way to get common types, such as Floats,doubles,intergers,booleans,urls. So a Nsuserdefaults object must be an attribute table, which means we can store nsdata,nsstring,nsnumber,nsdate,nsarray,nsdictionary these instances. If you want to store other types of objects, you need to archive them and create a nsdata to implement the storage.
The value returned from Nsuserdefaults is immutable, even if you are storing it with a variable value. For example, you use the mutable string as the value of "Mystringdefault", and when you do use the Stringforkey: method to get the value, the value is still immutable.
Nsuserdefaults is a singleton, but also thread-safe .
When using Nsuserdefaults, let's look at the following code:
NSDictionary * defaults = [[ NSUserDefaults standardUserDefaults] dictionaryRepresentation]; NSLog (@ "Defaults: %@" , defaults); |
Is the setting that is used to get all the nsuserdefaults on the device.
The above code outputs
Defaults: {
AppleITunesStoreItemKinds = (
eBook,
document,
"software-update"
,
booklet,
"itunes-u"
,
newsstand,
artist,
podcast,
"podcast-episode"
,
software
);
AppleKeyboards = (
"[email protected]=Pinyin;hw=US"
,
"[email protected]=US;sw=QWERTY"
);
AppleKeyboardsExpanded = 1;
AppleLanguages = (
"zh-Hans"
,
en,
fr,
de,
ja,
nl,
it,
es,
pt,
"pt-PT"
,
da,
fi,
nb,
sv,
ko,
"zh-Hant"
,
ru,
pl,
tr,
uk,
ar,
hr,
cs,
el,
he,
ro,
sk,
th,
id
,
"en-GB"
,
ca,
hu,
vi
);
|
If you want to see the settings for a key individually, for example:
NSArray *array = [[ NSUserDefaults standardUserDefaults] objectForKey:@ "AppleKeyboards" ]; NSLog (@ "Keyboards: %@" , array); |
Will output
AppleKeyboards = ( "[email protected]=Pinyin;hw=US" , "[email protected]=US;sw=QWERTY" ); |
Look at the code below.
if ([[ NSUserDefaults standardUserDefaults] objectForKey:@ "message" ]== nil ){ [[ NSUserDefaults standardUserDefaults] setObject:@ "This_is_my_default_message" forKey:@ "message" ]; } |
The code means to judge whether the Nsuserdefaults "message" key exists in the dictionaryrepresentation, and if it does not exist,
Set "message" Key to This_is_my_default_message.
Add a sentence [[Nsuserdefaults standarduserdefaults] synchronize], so this setting is stored in the default parameter.
Introduction and usage of iOS development learning-nsuserdefaults