Several methods of data persistence in iOS development--nsuserdefaults

Source: Internet
Author: User

Several methods of data persistence in iOS development--nsuserdefaults

IOS development, often encounter the need to keep some data in the local situation, then we have the following options to choose:

First, the use of Nsuserdefault is the simplest and direct approach:

1) Save the data:

1 //     Instantiate a nsuserdefaults singleton object 2     Nsuserdefaults *user = [Nsuserdefaults standarduserdefaults]; 3 //     Save an array of arrays in key-value pairs of allcontact 4     [User Setobject:array Forkey:@ "allcontact"]; 5 //     write directly to the drive 6     [User Synchronize];

2) Read the data:

1 //     Instantiate a nsuserdefaults singleton object 2     Nsuserdefaults *user = [Nsuserdefaults standarduserdefaults]; 3 //     put the array that is stored in the allcontact and take it out according to key 4     Nsarray *dataarray = [user objectforkey:@ "allcontact"];

Precautions:

In Apple's official documentation there is a clear explanation:

That is, it can only be deposited,,,, NSData NSString NSNumber NSDate NSArray , or NSDictionary . NSArrayfor and NSDictionary objects, their contents must is property list objects. These objects, and (. For NSArray and NSDictionary objects, their contents must is Property list objects.) such as arrays, the elements stored in the dictionary can only be the contents of these objects, how to customize a more complex instance of the class Like using Nsuserdefaults to save it? Here's how:

Using a mobile phone to contact human MyContact, for example, illustrates:

1) in the MyContact.h file, let the class comply with the Nscoding protocol:

1 //2 //myContact.h3 //Telephone book for the elderly4 //5 //Created by Mac on 16/5/3.6 //copyright©2016 year MZW. All rights reserved.7 //8 9 #import<Foundation/Foundation.h>Ten  One //To use a singleton nsuserdefault to store a custom object, first let the custom object adhere to the Nscoding protocol A @interfaceMycontact:nsobject<nscoding> -  -@property (nonatomic, copy) NSString *FirstName; the@property (nonatomic, copy) NSString *LastName; -@property (nonatomic, copy) NSString *PhoneNumber; -@property (nonatomic, copy) NSData *photo; -@property (nonatomic, copy) NSString *identify; + @property (nonatomic, assign) BOOL emergency; -  + @end

2) Implement two methods in the MYCONTACT.M file: Encodewithcoder and Initwithcoder methods

1 //2 //MYCONTACT.M3 //Telephone book for the elderly4 //5 //Created by Mac on 16/5/3.6 //copyright©2016 year MZW. All rights reserved.7 //8 9 #import "myContact.h"Ten  One @implementationMyContact A  - @synthesizeFirstName; - @synthesizeLastName; the @synthesizePhoneNumber; - @synthesizephoto; - @synthesizeidentify; - @synthesizeEmergency; +  --(void) Encodewithcoder: (Nscoder *) acoder{ +      A[Acoder encodeObject:self.firstname Forkey:@"FirstName"]; at[Acoder encodeObject:self.lastname Forkey:@"LastName"]; -[Acoder encodeObject:self.phoneNumber Forkey:@"PhoneNumber"]; -[Acoder EncodeObject:self.photo Forkey:@"Photo"]; -[Acoder encodeObject:self.identify Forkey:@"Identify"]; -[Acoder encodeBool:self.emergency Forkey:@"Emergency"];//Note that for Boolean types, you cannot use Encodeobject, and you want to use Encodebool for the corresponding type.  - } in  --(ID) Initwithcoder: (Nscoder *) adecoder{ to      +     if(self =[Super Init]) { -          theSelf.firstname = [Adecoder decodeobjectforkey:@"FirstName"]; *Self.lastname = [Adecoder decodeobjectforkey:@"LastName"]; $Self.phonenumber = [Adecoder decodeobjectforkey:@"PhoneNumber"];Panax NotoginsengSelf.photo = [Adecoder decodeobjectforkey:@"Photo"]; -Self.identify = [Adecoder decodeobjectforkey:@"Identify"]; theSelf.emergency = [Adecoder decodeboolforkey:@"Emergency"];//in the same vein, use Decodeboolforkey to correspond.  +     } A     returnSelf ; the}

3) to complete the above two steps, we can save the MyContact instance object by Nsuserdefaults: (The following program section involves both reading and saving after appending content)

1 //after the property value assignment is complete, you can use Nskeyedarchiver to package the object Mycontact1 as a NSData object2NSData *data =[Nskeyedarchiver Archiveddatawithrootobject:mycontact1];3 //Create and initialize a Nsuserdefaults singleton object4Nsuserdefaults *user =[Nsuserdefaults standarduserdefaults];5 //The value of the allcontact that was stored in before the user is read (an immutable array), and then because we want to append a contact's packaged NSData data to the array, we convert the array into a mutable array. 6Nsmutablearray *contactarray = [Nsmutablearray arraywitharray:[user objectforkey:@"allcontact"]];7 //append NSData data from the previously packaged contact MYCONTACT1 to the variable array contactarray8 [Contactarray Addobject:data];9 //and convert the mutable array to an immutable group .TenNsarray *array =[Nsarray Arraywitharray:contactarray]; One //Save the new array with the same key value before the allcontact corresponding value is replaced A[User Setobject:array Forkey:@"allcontact"]; - //write directly to the drive -[User Synchronize];

Note: The data saved by Nsuserdefaults is global, which also provides us with a means of managing global variables, such as saving some data on page A and using it in many other pages, which we can save with a singleton. This allows you to read the corresponding content by using the key value of the same nsuserdefaults on a different page. However, it is important to note that the saved data must be immutable, not mutable arrays, mutable strings, mutable dictionaries, and so on, or the program will produce unexpected errors.

Several methods of data persistence in iOS development--nsuserdefaults

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.