OC Language-Data Storage (archive &plist&json)

Source: Internet
Author: User
Tags object serialization

1. Introduction to data storage

usually the program is running, or after the program is finished, you need to save some information, It also requires persistent storage of information, such as login information, video playback records, Collect records and so on; we can persist the data in several ways.

A. Documentation

B.plist

C. Archiving

D.nsuserdefaults

E. Database

the next two approaches are plist and archiving.

2. Property list File Plist

(1) What is a plist file, the role of plist file

A. plist File: Property list file, the contents of the file can only be nsstring nsnumber nsdate nsdata nsarray nsdictionary class object Content, Other types of data cannot be saved.

B. Role: Persistent storage of some login registration information or program configuration information (small data) .

(2) How to create a plist file, how to edit a plist file

the format of plist file contents is XML syntax format;

A.creating a Plist file with code

If you want to put NSString nsnumber nsdate nsdata Nsarray Nsdictionary object is written to the file, generally use plist file;

we need to save this data in an array or dictionary first, then call the array and the dictionary related functions, put the array nsarray or dictionary nsdictionary, write plist file;

Nsarray and Nsdictionary Write file Method-(BOOL) WriteToFile: (NSString *) path atomically: (bool) useauxiliaryfile;

(3) How to read plist file data in a program

The root node of the plist file (the outermost layer of the data) is usually an array or dictionary;

1. If the root node of the plist file is a dictionary,

Then the class method using the dictionary

+ (ID) dictionarywithcontentsoffile: (NSString *) path;

To read the plist file;

2. If the root node is an array,

Then the class method using the array

+ (ID) arraywithcontentsoffile: (NSString *) path;

To read the plist file;

Note: the above two methods can only read the plist file and cannot read files in other formats.

3. File Archiving

(1) What is archive and file reconciliation

A. Archiving (also known as Object serialization, Object persistence storage) is the use of a packaged format to save an object to a local file so that it can be read back to the contents of that object later

B. A solution (also known as an archive/read file) is the process of reading an archived object file into the original object.

-"How to file and file a document

A. Archiving and documentation of system classes

Serialized Array Archive        nsarray *array = @[@ "Xiaohong", @ "IOS", @123];                NSString *path = @ "/users/sub/desktop/data.archive";//Archive process        BOOL success = [Nskeyedarchiver archiverootobject: Array Tofile:path];         if (success) {            NSLog (@ "Archive succeeded");              } else{            NSLog (@ "Archive failed");       }         Reverse sequence resolution file        nsarray *newarray = [Nskeyedunarchiver Unarchiveobjectwithfile:path];         

Note: Nsdictionary can also be directly archived and reconciled files; The archived objects include the properties in this object, all of the classes they belong to must comply with the Nscoding Archive protocol to archive and file the files;

B. Archive and file for custom classes

if the custom class object is to be archived, then the class that this object's property belongs to must also obey the Archive protocol nscoding, The following two methods must be implemented:

method to be called when archiving-(void) Encodewithcoder: (Nscoder *) Acoder; The method to be called when the file is unpacked-(ID) Initwithcoder: (Nscoder *) Adecoder;

eg. sample part code

#import <Foundation/Foundation.h> #import "Student.h" int main (int argc, const char * argv[]) {  @ Autoreleasepool {#if 0      //Archive and file operation of system type    nsdictionary* aDic = [[Nsdictionary alloc]initwithobjectsandkeys:@] Hello ", @" one ", @" haha ", @" one ", nil];    nsstring* path = @ "/users/sub/desktop/adic.archive";      Object archiving for System classes    [Nskeyedarchiver archiverootobject:adic Tofile:path];        nsdictionary* bDic = [Nskeyedunarchiver Unarchiveobrunjectwithfile:path];        NSLog (@ "bdic:%@", bDic);    NSLog (@ "adic:%@", ADic), #endif        student* aStu = [[Student alloc] init];    NSLog (@ "astu:%@", aStu);        nsstring* path = @ "/users/sub/desktop/astu.archive";        [Nskeyedarchiver Archiverootobject:astu Tofile:path];        student* bstu = [Nskeyedunarchiver Unarchiveobjectwithfile:path];    NSLog (@ "bstu:%@", BStU);          }    return 0;}

4. Json Storage

(1) What is JSON

JSON is a lightweight data interchange format, JSON syntax is a subset of JavaScript syntax;

the writing format for JSON data is: Name: Values form key-value pairs. (similar to the key-value pair for OC dictionaries)

(2) basic syntax for JSON

name/value pairs include field names (in double quotes), write a colon followed by a value. such as "FirstName": "Tom"

The value of JSON can be:

A. Number (integer or floating point)

B. String (in double quotes)

C. Logical value (TRUE or False)

D. Array (in square brackets)

E. Object (in curly braces)

F. Null

(3) JSON structure

JSON has two structures: array and dictionary ; these two structures can represent various complex structures;

A. Array:

The array in JS is the bracketed "[]" content, data structure for ["Js", "JavaScript", "VB", "VC", ...], similar to an array in OC .

B. Object:

object in JS is represented as "{}" in the content . data structure for {key:value, Key:value, ...} The structure of a key-value pair, similar to a dictionary in OC;

(4) JSON parsing

If there is a local file content format is in JSON format.

A. First Call

+ (ID) stringwithcontentsoffile: (NSString *) path

Encoding: (nsstringencoding) Enc

Error: (Nserror *) error; read the file into a string.

B. Then convert the string into NSData binary data;

C. Call the System class Nsjsonserialization

+ (ID) jsonobjectwithdata: (NSData *) data

Options: (nsjsonreadingoptions) opt

Error:  (Nserror *) error;

Parsing, and finally parsing to Nsarray or nsdictionary

Note:

The outermost layer of JSON data is usually a dictionary or an array, and the dictionary structure is mostly . use Nsjsonserialization to parse JSON data and parse it out as Nsarray or nsdictionary in OC.

eg. sample code

#import <foundation/foundation.h>int Main (int argc, const char * argv[]) {  @autoreleasepool {      //First step: Read JSON format file, into string    nsstring* json_des = [NSString stringwithcontentsoffile:@ "/users/sub/desktop/jiexi_json.txt" Encoding:nsutf8stringencoding Error:nil];      The second step: convert the above string into a NSData object    nsdata* aData = [Json_des datausingencoding:nsutf8stringencoding];      Step three: Submit the NSData object to the JSON parser parsing    nsdictionary* json_dic = [nsjsonserialization jsonobjectwithdata:adata options: Nsjsonreadingmutablecontainers Error:nil];      Using the for-in loop structure, traverse the print Dictionary for    (nsstring* key in Json_dic) {      NSLog (@ "key:%@ value:%@", Key,[json_dic objectfor Key:key]);    }      }    return 0;}

OC Language-Data Storage (archive &plist&json)

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.