Introduction to nsuserdefaults, using nsuserdefaults to store custom objects

Source: Internet
Author: User
1. Understand nsuserdefaults and the types it can directly store

Nsuserdefaults is a singleton. It has only one instance object in the entire program. It can be used for permanent data storage and is simple and practical. This is a prerequisite for free data transmission, this is also one of the main reasons why you like to use it to save simple data.

To use nsuserdefaults to store custom objects, we must first understand what types of data nsuserdefaults can store. The following lists them one by one:

Nsuserdefaults supports nsnumber (nsinteger, float, and double), nsstring, nsdate, nsarray, nsdictionary, and bool.


If you want to permanently Save the above data type data to nsuserdefaults, you only need a simple operation (one value and one key). For example, to save an nsstring object, the code is implemented as follows:


// Store the nsstring object in nsuserdefaults nsstring * Password = @ "1234567"; nsuserdefaults * user = [nsuserdefaults standarduserdefaults]; [user setobject: Password forkey: @ "userpassword"];


It is also easy to retrieve data. You only need to retrieve the value corresponding to the key. The Code is as follows:

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];    NSString *passWord = [ user objectForKey:@"userPassWord"];


Note: The assignment of the same key is approximately equal to one overwrite, and the uniqueness of each key must be ensured.


It is worth noting that:

The objects stored in nsuserdefaults are all immutable (this is critical and the program will have bugs if it is wrong). For example, if I want to store an nsmutablearray object, I must first create an unchangeable array (nsarray) and store it in nsuserdefaults. The Code is as follows:


Nsmutablearray * mutablearray = [nsmutablearray arraywithobjects: @ "123", @ "234", nil]; nsarray * array = [nsarray arraywitharray: mutablearray]; nsuserdefaults * user = [nsuserdefaults standarduserdefaults]; [user setobject: array forkey: @ "Remember to store it immutable"];


The retrieved data is the same. You want to assign a value to the variable array using the data in nsuserdefaults.

First, an incorrect syntax is provided:


/* ------------------------- Incorrect value assignment method ------------------- */nsuserdefaults * user = [nsuserdefaults standarduserdefaults]; // mutablearray becomes an unchangeable array, if you want to add or delete data in the array, the bug nsmutablearray * mutablearray = [user objectforkey: @ "Remember that the storage must be immutable" will occur.


Correct syntax:

/* Correct assignment method of callback */nsuserdefaults * user = [nsuserdefaults standarduserdefaults]; // you can use the alloc method to replace nsmutablearray * mutablearray = [nsmutablearray arraywitharray: [user objectforkey: @ "Remember that the storage must be immutable"];


Ii. Use nsuserdefaults to store the custom object 1. Convert the custom type to the nsdata type

When there are too many data records (for example, to store the student ID, name, and gender of the class (this data size may be too large )), if you do not need SQLite storage (it is best to use this option for multiple data types), you can use archive and then write the file locally, however, this method is much more troublesome than nsuserults ults (because nsfilemanage is complicated), but the problem is that nsuserdefaults itself does not support the storage of custom objects, but it supports the nsdata type, the following is an example.


First, create a class named student, which has three attributes (student ID, name, and gender ),

What we need to do is to convert the student type to the nsdata type, and archive must be implemented:

Here we need to declare the nscoding protocol in the. h file, and then implement the encodewithcoder method and

The initwithcoder method can be used:


Modify the file in. h:


Add code to. M:

In this way, you can change the custom type to the nsdata type.


2. Save custom data to nsuserdefaults

If you want to store the information of the class, you can create an nsmutablearray to store the information of the class (all the nsdata objects are stored in it) and add the Code where the class is stored:

// First, you need to create a variable array to store the nsdate object student * student = [[STUDENT alloc] INI]; // The Name Of The Student object, studentnumber, sex assignment student. name = @ "lady-yi"; student. studentnumber = @ "3100104006"; student. sex = @ "female"; // This is an array of nsmutablearray * dataarray = [nsmutablearray arraywithcapacity: 50]; // change the student type to the nsdata type nsdata * Data = [nskeyedarchiver archiveddatawithrootobject: Student]; // Add the data to the data array [dataarray addobject: Data];


If you only want to save one person's information, you can directly store nsdata into nsuserdefaults:

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:student];           NSUserDefaults *user = [NSUserDefaults standardUserDefaults];    [user setObject:data forKey:@"oneStudent"];


If you want to store the information of the class, you need to use a for loop to put data into dataarray. The specific operation here is not implemented. Only the stored code is provided:

// Remember to convert to an unchangeable array type nsarray * array = [nsarray arraywitharray: dataarray]; nsuserdefaults * user = [nsuserdefaults standarduserdefaults]; [user setobject: array forkey: @ "allstudent"];


Retrieving data from nsuserdefaults is easy to restore.

For example, to restore the data of a student:

NSUserDefaults *user = [NSUserDefaults standardUserDefaults];  NSdData *data = [user objectForKey:@"oneStudent"];     Student *student = [NSKeyedUnarchiver unarchiveObjectWithData:data];


In short, nsuserdefaults is the most common method for permanent data storage in our code writing, and it is also the simplest.


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.