iOS app data storage method (archive)

Source: Internet
Author: User

iOS app data storage method (archive)

A simple explanation

In the use of plist for data storage and reading, only applicable to some of the system's own common types to use, and must first get the path relative trouble; preferences (keep everything under the same folder and primarily store app settings information) Archive: Because the first two have a fatal flaw, Only the commonly used types can be stored. Archiving allows you to store your custom objects in a file.

Second, code example

1. File structure

2. Code examples

YYVIEWCONTROLLER.M file

  9 #import "YYViewController.h" #import "YYPerson.h" @interface Yyviewcontroller ()-(Ibaction) Savebtnonclick: ( ID) sender;14-(Ibaction) Readbtnonclick: (ID) sender;15 @end17 @implementation YYViewController19-(void) viewDidLoad21 {[Super viewdidload];23}24-(ibaction) Savebtnonclick: (ID) Sender {27//1. Create Object Yypers On *p=[[yyperson alloc]init];29 [email protected] "Top of text"; p.age=23;31 p.height=1.7;32 33//2. Get file Path NSString *docpath=[nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) LastObject]      ; NSString *path=[docpath stringbyappendingpathcomponent:@ "Person.yangyang"];36 NSLog (@ "path=%@", Path); 37 38 3. Saving a custom object to a file [nskeyedarchiver archiverootobject:p tofile:path];40}42-(ibaction) Readbtnonclick :(ID) Sender {44//1. Get file path NSString *docpath=[nssearchpathfordirectoriesindomains (NSDocumentDirectory, NSUserDom Ainmask, YES) lastobject];46 nsstring *path=[docpath stringbyappendingpathcomponent:@ "Person.yangyang"];47 NSLog (@ "path=%@", Path); 48 49//2. From the file Read Object Yyperson *p=[nskeyedunarchiver unarchiveobjectwithfile:path];51 NSLog (@ "%@,%d,%.1f", p.name,p.age,p.height); }53 @end

Create a new Person class

YYPerson.h file

8  9 #import <foundation/foundation.h>10 11//If you want to save a custom object to a file, you must implement Nscoding protocol @interface Yyperson: Nsobject<nscoding>13 14//Name @property (nonatomic,copy) NSString *name;16//Age @property (nonatomic,assign) int age;18//height @property (nonatomic,assign) Double height;20 @end

YYPERSON.M file

8  9 #import "YYPerson.h" @implementation YYPerson12 13//The method is called when a custom object is saved to a file 14//In this method describes how to store the properties of a custom object 15// It is also said in this method that it is clear which properties of the custom object are stored (void) Encodewithcoder: (Nscoder *) aCoder17 {     NSLog (@ "called Encodewithcoder: Method"); 19     [Acoder encodeObject:self.name forkey:@ "name"];20     [Acoder encodeInteger:self.age forkey:@ "age"];21     [acoder encodeDouble:self.height forkey:@ "height"];22}23 24// This method is called when an object is read from a file 25//In this method describes how to read an object saved in a file 26//That is, in this method it is clear how to read the object in the file-(ID) Initwithcoder: (Nscoder *) aDecoder28 {     NSLog (@ "called Initwithcoder: Method");     Note: The method of the parent class needs to be initialized first in the constructor method,     if (self=[super init]) {32         self.name=[adecoder decodeobjectforkey:@ "name"];33         self.age=[adecoder decodeintegerforkey:@ "age"];34         self.height=[adecoder decodedoubleforkey:@ "height"];35     }     return self;37}38 @end

3. Printing effects and two important error hints

Click the Save button and the Read button to successfully print the results as follows:

For an error message that does not implement two protocol methods:

-(void) Encodewithcoder: (Nscoder *) Acoder method:

-(ID) Initwithcoder: (Nscoder *) Adecoder method:

Third, the use of the inheritance class

Create a new student class, and let this class inherit from the Preson class, adding a weight attribute.

YYstudent.h file

9 #import "YYPerson.h" @interface yystudent:yyperson12//Add a weight attribute of @property (nonatomic,assign) Double weight;14 @e nd

YYSTUDENT.M file

9 #import "YYstudent.h" @implementation YYstudent12 13//Override both methods in subclasses-(void) Encodewithcoder: (Nscoder *) ACoder15 {     [Super encodewithcoder:acoder];17     NSLog (@ "called Yystudent Encodewithcoder");     [Acoder encodefloat: Self.weight forkey:@ "Weight"];19}20-(ID) Initwithcoder: (Nscoder *) ADecoder22 {     if (self = [Super Initwithcoder : Adecoder]) {         NSLog (@ "called Yystudent Initwithcoder");         self.weight = [Adecoder decodefloatforkey:@ "Weight" ];26     }27     return self;28}29 @end

YYVIEWCONTROLLER.M file

 8 9 #import "YYViewController.h" #import "YYPerson.h" #import "YYstudent.h" @interface Yyviewcontroller () 14- (ibaction) Savebtnonclick: (ID) sender;15-(Ibaction) Readbtnonclick: (ID) sender;16 @end18 @implementation  YYViewController20-(void) viewDidLoad22 {[Super viewdidload];24}25-(ibaction) Savebtnonclick: (ID) sender    {28//1. Create Object//Yyperson *p=[[yyperson alloc]init];30//[email protected] "Top of text";//P.AGE=23;32// p.height=1.7;33 yystudent *s=[[yystudent alloc]init];35 [email protected] "wendingding"; s.age =23;37 s.height=1.7;38 s.weight=62;39//2. Get file path all NSString *docpath=[nssearchpathfordirectoriesindomains ( NSDocumentDirectory, Nsuserdomainmask, YES) lastobject];41 nsstring *path=[docpath stringbyappendingpathcomponent:@ " Person.yangyang "];42 NSLog (@" path=%@ ", Path); 43 44//3. To save a custom object to a file [Nskeyedarchiver archiverootobject :p tofile:path];46 [Nskeyedarchiver Archiverootobject:s tofile:path];47}49-(ibaction) Readbtnonclick: (ID) Sender {51//1. Get the file path, NSString *docpath=[nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastObject];53 NSString * Path=[docpath stringbyappendingpathcomponent:@ "Person.yangyang"];54 NSLog (@ "path=%@", path); 55 56//2. Reading objects from a file 5 7//Yyperson *p=[nskeyedunarchiver unarchiveobjectwithfile:path];58//NSLog (@ "%@,%d,%.1f", p.name,p.age,p.height); 5 9 yystudent *s=[nskeyedunarchiver unarchiveobjectwithfile:path];60 NSLog (@ "%@,%d,%.1f,%f", S.name,s.age,s.height,s. weight);}62 @end

Click the Save button and the print output after reading the button:

Iv. Important Notes

1. Save the data process:

    1. Create Object    yystudent *s=[[yystudent alloc]init];    [Email protected] "wendingding";    s.age=23;    s.height=1.7;    s.weight=62;        2. Get file path    nsstring *docpath=[nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) Lastobject];    NSString *path=[docpath stringbyappendingpathcomponent:@ "Person.yangyang"];    NSLog (@ "path=%@", path);        3. Save the custom object to a file     [Nskeyedarchiver archiverootobject:s Tofile:path];

2. Read the data process:

1. Get file path    nsstring *docpath=[nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) Lastobject];    NSString *path=[docpath stringbyappendingpathcomponent:@ "Person.yangyang"];    2. Reading objects from a file    yystudent *s=[nskeyedunarchiver Unarchiveobjectwithfile:path];

3. Comply with the Nscoding agreement and implement the two methods in the agreement.

4. In the case of inheritance, the subclass must override the two methods. Because the child of the person in the access time, will go to the subclass to find the method of invocation, not found then it went to the parent class, so the last time to save and read the new properties will be ignored. You need to call the parent class's method first, initialize the parent class, and then initialize the subclass.

5. The suffix name of the file that holds the data can be named arbitrarily.

6. Data saved through Plist is displayed directly and is not secure. The data saved by the archive method is garbled and more secure when it is opened in a file.

iOS app data storage method (archive)

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.