Use of nsuserdefault

Source: Internet
Author: User

Note: Thank you.Define_feeling, IOS Didi, Apache, and thanks for their summary of the use of nsuserdefault.

1. Use nsuserdefault:

Purpose: The nsuserdefaults class provides a programming interface for interacting with the default system. The nsuserdefaults object is used to save and restore preference settings and configuration data related to the application. By default, the system allows applications to customize their behaviors to suit users' preferences. You can read the program settings from the user's default database when the program is running. At the same time, the nsuserdefaults cache avoids enabling the user's default database every time the data is read. You can call the synchronize method to synchronize the cache in the memory with the user's default system.

Principle: nsuserdefault is lightweight data persistence for users. It is mainly used to save user program configurations and other information, so that the last setting can be restored after the program is started next time. Because it is written to the hard disk, too much will cause system waste, memory usage and other problems.

(1) The data is actually saved in the form of a "key-Value Pair" (similar to nsdictionary), so we need to use the key to read or save the data (value ).

(2) The nsuserdefaults class provides very convenient methods to obtain common types, such as floats, doubles, intergers, booleans, and URLs. Therefore, we can store nsdata, nsstring, nsnumber, nsdate, nsarray, and nsdictionary instances (currently there are five types. If you want to store other types of objects, You need to archive them and create an nsdata for storage.

(3) The value returned from nsuserdefaults cannot be changed, even if you are using a variable value during storage. For example, if you use mutable string as the value of "mystringdefault", the value obtained by using the stringforkey: method is still unchangeable.

(4) nsuserdefaults is a singleton and thread-safe

Syntax:

Example of an integer storage:

1. Obtain an nsuserdefaults reference:

Nsuserdefaults * userdefaults = [nsuserdefaults standarduserdefaults];

2. Save data

[Userdefaults setinteger: 1 forkey: @ "segment"];

 

[Userdefaults synchronize];

3. Read data

Int I = [userdefaults integerforkey: @ "segment"];

Example of storing other data types:

Save data: If the uicolor type is saved and the preceding five data types are exceeded, archive them into data types before saving them.

 

Nsdata * objcolor = [nskeyedarchiver archiveddatawithrootobject: [uicolor redcolor];

[[Nsuserdefaults standarduserdefaults] setobject: objcolor forkey: @ "mycolor"];

 

Read data:

 

Nsdata * objcolor = [[nsuserdefaults standarduserdefaults] objectforkey: @ "mycolor"];

 

Uicolor * mycolor = [nskeyedunarchiver unarchiveobjectwithdata: objcolor];

2. Tips for using nsuserdefault:

(1) The data saved by nsuserdefault can be successfully read before the program is closed, but cannot be read after the application is restarted because the data is not written in real time.You can see through the official documentation,UserdefaultsThe cache data is written to the local disk according to the timestamp instead of the real-time data. ThereforeSetAfter the method, the data may not be written to the disk, and the application is terminated. During the warranty period, we useSynchornizeMethod. However, you should also note that you do not need to use it frequently.Synchornize.

 

(2 ),In useNsuserdefaultMany people think that:

[[Nsuserdefaults standarduserdefaults] setobject: array forkey: @ "testinfo"];

After that, you can use

[[Nsuserdefaults standarduserdefaults] objectforkey: @ "testinfo"];

You can retrieve the data you just saved.

 

In fact, there is no problem under normal circumstances, but when it starts again

Program, keywordTestinfoThe corresponding information is empty. What is the situation ??

 

Let's seeNsuserdefaultsHeader file, you will find that there is another method:Synchronize, Real-time data writing.

 

If weSetThen, execute the following statement:

[[Nsuserdefaults standarduserdefaults] synchronize];

In this case, the data retrieved above will not be empty.

 

The complete code is as follows:

// Store data

Nsuserdefaults *Ults=[NsuserdefaultsStandarduserdefaults];

[Defaults setobject:@"111"Forkey:@"T

Est"];

//Write Data to the hard disk

[Defaults synchronize];

 

// Retrieve data

Nsstring *Teststr=[Defaults objectforkey:@"Test"];

Nslog(@"Teststr is: % @",Teststr);

3. Some actual use of nsuserdefault:

When using nsuserdefaults,

Let's take a look at the following code.

Nsdictionary * defaults = [[nsuserdefaults standarduserdefaults] dictionaryrepresentation];

Nslog (@ "defaults: % @", defaults );

Is used to get all nsuserults ults settings on the device.

The above code is output

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 view the settings of a key separately, for example:

Nsarray * array = [[nsuserdefaults standarduserdefaults] objectforkey: @ "applekeyboards"];

Nslog (@ "keyboards: % @", array );

Output

Applekeyboards = (

"[Email protected] = pinyin; hW = us ",

"[Email protected] = US; Sw = Qwerty"

);

Check the following code:

If ([[nsuserdefaults standarduserdefaults] objectforkey: @ "message"] = nil ){

[[Nsuserdefaults standarduserdefaults] setobject: @ "this_is_my_default_message" forkey: @ "message"];

}

The Code determines whether the "message" Key of nsuserdefaults exists in dictionaryrepresentation. If it does not exist

Set "message" key to this_is_my_default_message.

Add [[nsuserdefaults standarduserdefaults] synchronize]; To save this setting to the default parameter.

 

I have also seen other people write the settings of the default parameters to the registration of applicationdidfinishlaunching,

-(Void) applicationdidfinishlaunching :( nsnotification *) anotification

{

Nsdictionary * defaultvalues = [nsdictionary dictionarywithobjectsandkeys:

@ "This_is_my_default_message", @ "message ",

Nil];

 

[[Nsuserdefaults standarduserdefaults] registerdefaults: defaultvalues];

[[Nsuserdefaultscontroller shareduserdefaultscontroller] setinitialvalues: defaultvalues];

}

Of course, registration in applicationdidfinishlaunching is the same as that in applicationdidfinishlaunching, but the code is beautiful.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.