Nsuserdefaults Introduction, using Nsuserdefaults to store custom objects

Source: Internet
Author: User

First, understand the nsuserdefaults and the types it can store directly

Nsuserdefaults is a singleton, in the whole program only one instance object, he can be used for the permanent preservation of data, and simple and practical, this is it can let the data free transfer of a premise, but also people like to use it to save simple data one of the main reasons.

When using Nsuserdefaults to store custom objects initially, we must recognize what types of data nsuserdefaults can store, listed below:

The data types supported by Nsuserdefaults are: NSNumber (Nsinteger, float, double), Nsstring,nsdate,nsarray,nsdictionary,bool.

If you want to permanently save the data of the above data type to Nsuserdefaults, you only need to do a simple operation (a value a key), for example, to save a NSString object, the code is implemented as:

1234     //将NSString 对象存储到 NSUserDefaults 中    NSString *passWord = @"1234567";    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];    [user setObject:passWord forKey:@"userPassWord"];

It is also very simple to remove the data, just need to take out the value corresponding to the key, the code is as follows:

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

Note: The same key assignment is approximately equal to one overwrite, to guarantee the uniqueness of each key

It is worth noting that:

Nsuserdefaults stored objects are immutable (this is critical, the program will bug if you make a mistake), for example, if I want to store a Nsmutablearray object, I must first create an immutable group (Nsarray) and then put it into Nsuserdefaults, the code is as follows:

?
12345      Code class= "CPP Plain" >nsmutablearray *mutablearray = [nsmutablearray arraywithobjects:@ "123" ,@ "234" , nil];      nsarray * array = [nsarray arraywitharray:mutablearray];             nsuserdefaults *user = [nsuserdefaults  Standarduserdefaults];      [user setobject:array forkey:@ "Remember that the storage must be immutable"

Remove data is the same, you want to use the data in the Nsuserdefaults to assign values to the variable array

Let's start with a wrong wording:

12345     /*-------------------------错误的赋值方法-------------------*/    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];        //这样写后,mutableArray 就变成了不可变数组了,如果你要在数组中添加或删除数据就会出现bug    NSMutableArray *mutableArray = [user objectForKey:@"记住存放的一定是不可变的"];

The correct wording:

?
12345     /*-------------------------正确的赋值方法-------------------*/    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];        //可以用alloc 方法代替    NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:[user objectForKey:@"记住存放的一定是不可变的"]];

Ii. using Nsuserdefaults to store custom objects 1, converting custom types to NSData types

When the data is repeated and many times (for example, you want to store the class number, name, gender (this amount of data may be too large)), if you do not use SQLite storage (most of it is best to use this), you can choose the archive, and then write the file locally, but this way and nsuserdefaults More trouble than it is (because nsfilemanage is inherently complicated), but the problem is that Nsuserdefaults itself does not support the storage of custom objects, but it supports the types of NSData, as described in the following example.

We first set up a class called student, which has three attributes (school number, name, gender),

All we have to do is change the student type to NSData type, then we have to implement the archive:

This is accomplished by declaring the Nscoding protocol in the. h file, and then implementing the Encodewithcoder method in. M and

The Initwithcoder method is available:

Modify files in. h:

Add code in. M:

By doing this, you can turn the custom type into a nsdata type.

2. Storing custom type data in Nsuserdefaults

If we want to store the information of the class, we can build a nsmutablearray to store the information of the class (all the NSData objects are stored) and add the code where it needs to be stored:

1234567891011121314151617 //首先,要建立一个可变数组来存储 NSDate对象     Student *student = [[Student alloc] ini];         //下面进行的是对student对象的 name , studentNumber ,sex 的赋值    student.name = @"lady-奕奕";    student.studentNumber = @"3100104006";    student.sex = @"女";        //这是一个存放全班同学的数组    NSMutableArray * dataArray = [NSMutableArray arrayWithCapacity:50];         //将student类型变为NSData类型    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:student];        //存放数据的数组将data加入进去    [dataArray addObject:data];

If you only want to save a person's information, you can directly deposit the NSData into the nsuserdefaults:

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

If you want to store the information of the whole class, you also need to use a for loop to put data into DataArray, where the specific operation is not implemented, just give the stored code:

?
12345    //记住要转换成不可变数组类型    NSArray * array = [NSArray arrayWithArray:dataArray];        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];    [user setObject:array forKey:@"allStudent"];

Extracting data from Nsuserdefaults is easy to restore.

For example, to restore a student's data:

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

In short, nsuserdefaults is the most common method of storing data permanently in our code and is the simplest.

Nsuserdefaults Introduction, using Nsuserdefaults to store custom objects

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.