In-depth explanation of how data is stored in IOS development _ios

Source: Internet
Author: User
Tags inheritance list of attributes reserved xml attribute

XML attribute list-plist
First, the application of sand box
each iOS application has a ⾃ ⽤ sandbox (the application sandbox is the file system directory) and is isolated from other file systems. Should ⽤ must stay in ⾃ 's sandbox, other applications cannot access the sandbox (hint: open access in IOS8)

The file system ⽬ of the sandbox should be ⽤, as shown in the following figure (assuming the name of the application is called layer)

The simulator should be ⽤ with the root path of the sandbox: (Apple is ⽤ username, 7.0 is the emulator version)/users/apple/library/application Support/iphone simulator/7.0/applications

Second, the application of sand box structure analysis

The package should be ⽤: (layer in the image above) contains all the resource files and executable files

Documents: Save the data that needs to be persisted at the ⽤ runtime, and the itunes synchronization device backs up the directory. For example, a game application can save a game archive in that directory

TMP: Save the temporary data that should be ⽤ at run time so that the ⽤ is finished before removing the appropriate files from the directory. When the application is not running, the system may also purge files from the directory. The itunes Sync device does not back up the directory

Library/caches: Saves data that needs to be persisted when the application runs ⽣, and the itunes Sync device does not back up the directory. ⼀ General storage of non-critical data that is large and does not need to be backed up

Library/preference: Save all the preferences for the application, and the settings for iOS should ⽤ the ⺫ record to find the setting information that should be ⽤. This directory is backed up by the itunes Sync device

Third, the application of the common way to get sand box

Sandbox root: NSString *home = Nshomedirectory ();
Documents: (2 kinds of ⽅ way)

Stitching the "Documents" string with the sandbox root directory

Copy Code code as follows:

NSString *home = Nshomedirectory ();
NSString *documents = [Home stringbyappendingpathcomponent:@ "documents"]; Not recommended because the new version of the operating system may modify the directory name

Using the Nssearchpathfordirectoriesindomains function
Copy Code code as follows:

Nsuserdomainmask representative from the user folder to find
YES represents the wave character "~" in the Expand path
Nsarray *array = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, NO); In iOS, only one directory matches the parameters passed in, so there is only one element in the set

NSString *documents = [array objectatindex:0];

Tmp:nsstring *tmp = Nstemporarydirectory ();


Library/caches: (2 kinds of ⽅ methods similar to documents)

Stitching the "caches" string with the sandbox root

⽤nssearchpathfordirectoriesindomains function (change the function's 2nd argument to: Nscachesdirectory)

Library/preference: Access to Settings information in this directory through the Nsuserdefaults class

The appropriate code:

Copy Code code as follows:

#import "NJViewController.h"
#import "NJPerson.h"

@interface Njviewcontroller ()
-(Ibaction) Savedatabtnclick: (ID) sender;
-(Ibaction) Readdatabtnclick: (ID) sender;

@end


Copy Code code as follows:

@implementation Njviewcontroller
/**
* Click the Save button
*/
-(Ibaction) Savedatabtnclick: (ID) Sender {

YouTube practices
NSString *path = @ "/users/apple/library/application support/iphone simulator/7.1/applications/ A6d53e11-ddf0-4392-b2d4-fe77a96888a6/documents/abc.plist ";

Get the application root directory
NSString *home = Nshomedirectory ();

Do not recommend writing/
NSString *path = [Home stringbyappendingstring:@ "/documents"];
Do not recommend documents written dead
NSString *path = [Home stringbyappendingpathcomponent:@ "Documents"];

Nsuserdomainmask Search in User directory
YES represents the user directory's ~
NSDocumentDirectory Find Documents folder
It is recommended that you use the following methods to dynamically obtain
NSString *doc = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) lastObject];
Stitching file paths
NSString *path = [Doc stringbyappendingpathcomponent:@ "Abc.plist"];
NSLog (@ "%@", Path);


Nsarray *arr = @[@ "Lnj", @ "28"];
[arr Writetofile:path Atomically:yes];

Nsdictionary *dict = @{@ "name": @ "LNJ", @ "age": @ "28"};
Call WriteToFile to write data to a file
[Dict Writetofile:path Atomically:yes];

/*
Plist can only store some of the regular classes that the system takes, that is, an object with WriteToFile methods to save data using plist
string/dictionary/Data/nsnumber/nsdata ...
*/

Custom objects cannot be saved to plist
Njperson *p = [[Njperson alloc] init];
P.name =@ "LNJ";

Nsdictionary *dict = @{@ "person": @ "abc"};
[Dict Writetofile:path Atomically:yes];
}
/**
* Click on the Read button
*/
-(Ibaction) Readdatabtnclick: (ID) Sender {
NSString *doc = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) lastObject];

NSString *path = [Doc stringbyappendingpathcomponent:@ "Abc.plist"]
;
Reading data
Nsdictionary *dict = [Nsdictionary Dictionarywithcontentsoffile:path];
NSLog (@ "%@", dict);
}
@end

iv. List of attributes

A property list is an XML-formatted file that expands to the name plist

If the object is of type NSString, Nsdictionary, Nsarray, NSData, NSNumber, you can write the object directly to the property list file using the Writetofile:atomically:⽅ method


Nskeydearchiver Archive
One, simple explanation

In the use of plist data storage and reading, only applicable to the system with some of the common types to use, and must first obtain the path relative trouble;
Preferences (keep everything under the same folder, and primarily to store settings for the application)
Archiving: Because the first two have a fatal flaw, you can only store commonly used types. Archiving enables you to store your custom objects in a file.
Second, the code example

1. Document structure

Copy Code code as follows:

//
Yyviewcontroller.m
02-Archive
//
Created by Apple on 14-6-7.
Copyright (c) 2014 itcase. All rights reserved.
//

#import "YYViewController.h"
#import "YYPerson.h"

@interface Yyviewcontroller ()
-(Ibaction) Savebtnonclick: (ID) sender;
-(Ibaction) Readbtnonclick: (ID) sender;

@end


Copy Code code as follows:

@implementation Yyviewcontroller

-(void) viewdidload
{
[Super Viewdidload];
}


-(ibaction) Savebtnonclick: (ID) Sender {
   //1. Create Object
    Yyperson *p=[[ Yyperson Alloc]init];
    p.name=@ "Top of the text";
    p.age=23;
    p.height=1.7;
   
   //2. Get file path
    nsstring *docpath=[ Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastobject];
    nsstring *path=[docpath stringbyappendingpathcomponent:@ "Person.yangyang"];
    NSLog (@ "path=%@", Path);
   
   //3. Save a custom object to a file
    [nskeyedarchiver Archiverootobject:p Tofile:path];
   
}

-(Ibaction) Readbtnonclick: (ID) Sender {
1. Get File path
NSString *docpath=[nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastObject];
NSString *path=[docpath stringbyappendingpathcomponent:@ "Person.yangyang"];
NSLog (@ "path=%@", Path);

2. Reading objects from files
Yyperson *p=[nskeyedunarchiver Unarchiveobjectwithfile:path];
NSLog (@ "%@,%d,%.1f", p.name,p.age,p.height);
}
@end


Create a new Person class

YYPerson.h file

Copy Code code as follows:

//
YYPerson.h
02-Archive
//
Created by Apple on 14-6-7.
Copyright (c) 2014 itcase. All rights reserved.
//

#import <Foundation/Foundation.h>

If you want to save a custom object to a file, you must implement the Nscoding protocol
@interface yyperson:nsobject<nscoding>

Name
@property (nonatomic,copy) NSString *name;
Age
@property (nonatomic,assign) int age;
Height
@property (nonatomic,assign) double height;
@end


YYPERSON.M file
Copy Code code as follows:

//
Yyperson.m
02-Archive
//
Created by Apple on 14-6-7.
Copyright (c) 2014 itcase. All rights reserved.
//

#import "YYPerson.h"

@implementation Yyperson

This method is called when a custom object is saved to a file
Describes how to store properties of custom objects in this method
It says in this method that it is clear which properties of the stored custom object
-(void) Encodewithcoder: (Nscoder *) Acoder
{
NSLog (@ "called Encodewithcoder: Method");
[Acoder encodeObject:self.name forkey:@ "name"];
[Acoder encodeInteger:self.age forkey:@ "age"];
[Acoder encodeDouble:self.height forkey:@ "height"];
}

This method is invoked when an object is read from a file
Describes how to read objects saved in a file in this method
That is, in this method, it's clear how to read objects in a file.
-(ID) Initwithcoder: (Nscoder *) Adecoder
{
NSLog (@ "called Initwithcoder: Method");
Note: Methods in the construction method that need to initialize the parent class first
if (Self=[super init]) {
Self.name=[adecoder decodeobjectforkey:@ "name"];
Self.age=[adecoder decodeintegerforkey:@ "age"];
Self.height=[adecoder decodedoubleforkey:@ "height"];
}
return self;
}
@end


3. Printing effect and two important error tips

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

About error tips for not implementing two protocol methods:

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

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

Iii. use in the Inheritance class

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

YYstudent.h file

Copy Code code as follows:

//
YYstudent.h
02-Archive
//
Created by Apple on 14-6-7.
Copyright (c) 2014 itcase. All rights reserved.
//

#import "YYPerson.h"

@interface Yystudent:yyperson
Add a weight attribute
@property (nonatomic,assign) double weight;
@end


YYSTUDENT.M file
Copy Code code as follows:

//
Yystudent.m
02-Archive
//
Created by Apple on 14-6-7.
Copyright (c) 2014 itcase. All rights reserved.
//

#import "YYstudent.h"

@implementation Yystudent

Override these two methods in a subclass
-(void) Encodewithcoder: (Nscoder *) Acoder
{
[Super Encodewithcoder:acoder];
NSLog (@ "called the Yystudent Encodewithcoder");
[Acoder encodeFloat:self.weight forkey:@ "weight"];
}

-(ID) Initwithcoder: (Nscoder *) Adecoder
{
if (self = [Super Initwithcoder:adecoder]) {
NSLog (@ "called the Yystudent Initwithcoder");
Self.weight = [Adecoder decodefloatforkey:@ "weight"];
}
return self;
}
@end


YYVIEWCONTROLLER.M file
Copy Code code as follows:

//
Yyviewcontroller.m
02-Archive
//
Created by Apple on 14-6-7.
Copyright (c) 2014 itcase. All rights reserved.
//

#import "YYViewController.h"
#import "YYPerson.h"
#import "YYstudent.h"

@interface Yyviewcontroller ()
-(Ibaction) Savebtnonclick: (ID) sender;
-(Ibaction) Readbtnonclick: (ID) sender;

@end


Copy Code code as follows:

@implementation Yyviewcontroller

-(void) viewdidload
{
[Super Viewdidload];
}


-(Ibaction) Savebtnonclick: (ID) Sender {
1. Creating objects
Yyperson *p=[[yyperson Alloc]init];
p.name=@ "Wen ding Ding";
p.age=23;
p.height=1.7;

Yystudent *s=[[yystudent Alloc]init];
s.name=@ "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 a custom object to a file
[Nskeyedarchiver archiverootobject:p Tofile:path];
[Nskeyedarchiver archiverootobject:s Tofile:path];

}

-(Ibaction) Readbtnonclick: (ID) Sender {
1. Get File path
NSString *docpath=[nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastObject];
NSString *path=[docpath stringbyappendingpathcomponent:@ "Person.yangyang"];
NSLog (@ "path=%@", Path);

2. Reading objects from files
Yyperson *p=[nskeyedunarchiver Unarchiveobjectwithfile:path];
NSLog (@ "%@,%d,%.1f", p.name,p.age,p.height);
Yystudent *s=[nskeyedunarchiver Unarchiveobjectwithfile:path];
NSLog (@ "%@,%d,%.1f,%f", s.name,s.age,s.height,s.weight);
}
@end


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

Iv. Important Notes

1. Save Data process:

Copy Code code as follows:

1. Creating objects
Yystudent *s=[[yystudent Alloc]init];
s.name=@ "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 a custom object to a file
[Nskeyedarchiver archiverootobject:s Tofile:path];

2. Read the data process:
Copy Code code as follows:

1. Get File path
NSString *docpath=[nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastObject];
NSString *path=[docpath stringbyappendingpathcomponent:@ "Person.yangyang"];
2. Reading objects from files
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 subclass of person will find the calling method in the subclass when it is accessed, it will find it in the parent class, so the newly added attributes will be ignored when the last save and read. You need to call the method of the parent class first, initialize the parent class, and then initialize the subclass.

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

6. The data saved through the plist is directly displayed and unsafe. Data saved through the archive method is garbled and more secure in the file.

Related Article

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.