Archive files for iOS

Source: Internet
Author: User

The previous articles talked about the foundation framework in OC: http://blog.csdn.net/jiangwei0910410003/article/details/41852835, let's take a look at an important point in OC: Archive

The archive in OC is to write the object to a file, ObjectInputStream and ObjectOutputStream in Java to operate. Of course, these objects in action are required to implement an interface: Serializable, the same OC in the operation of the object is also required to implement a protocol, it will be said later.

I. Existing types of archive and file reconciliation

Let's start with a simple example:

main.m//33_objecttofile////Created by Jiangwei on 14-10-13.//Copyright (c) 2014 Jiangwei. All rights reserved.//#import <foundation/foundation.h>//Archive: Writes an object to the file int main (int argc, const char * argv[]) {@ Autoreleasepool {///First form: Archive object//Object----"File *//Nsarray *array = [Nsarray arraywithobjects:@" Zhang        @ "Wangwu", @ "Lisi", nil];                NSString *filepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "ARRAY.SRC"];        BOOL success = [Nskeyedarchiver Archiverootobject:array Tofile:filepath];        if (success) {NSLog (@ "Save succeeded");        } */* nsstring archive *filepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "ARRAY.SRC"];        ID array = [nskeyedunarchiver Unarchiveobjectwithfile:filepath];         NSLog (@ "%@", array); *////////////The first way of defect is that an object is archived into a file//But in the second way, multiple objects can be archived as a file/* Nsarray *array = [ Nsarray arraywithobjects:@ "Zhangsan", @ "Lisi", nil];        Nsmutabledata *data = [Nsmutabledata data];        Nskeyedarchiver *archiver = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:data];        Encode [archiver encodeobject:array forkey:@ "Array"];        [Archiver encodeint:100 forkey:@ "Scope"];                [Archiver encodeobject:@ "Jack" forkey:@ "name"];        Complete the encoding to populate the above archived data into data, at which time the archived objects are already stored in database [Archiver finishencoding];                [Archiver release];        NSString *filepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "ARRAY.SRC"];        BOOL success = [data Writetofile:filepath atomically:yes];        if (success) {NSLog (@ "Archive succeeded");        } */NSString *filepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "ARRAY.SRC"];                Read archived data NSData *data = [[NSData alloc] initwithcontentsoffile:filepath]; Create a solution archive object to extract data from nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc] Initforreadingwithdata:dATA];        Solution archive Nsarray *array = [unarchiver decodeobjectforkey:@ "Array"];                NSLog (@ "%@", array);        int value = [unarchiver decodeobjectforkey:@ "Scope"];                            NSLog (@ "%d", value); } return 0;}

1. Archive

First form: Archive object//Object----"file Nsarray *array = [Nsarray arraywithobjects:@" Zhang ", @" Wangwu ", @" Lisi ", nil]; NSString *filepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "array.src"];  BOOL success = [Nskeyedarchiver Archiverootobject:array Tofile:filepath]; if (success) {     NSLog (@ "saved successfully");}

Here we will write a Nsarray object into a file.

Here's how to create a file:

NSString *filepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "ARRAY.SRC"];

We can print out the value of the filepath:

Nshomedirectory () returns the current user path

Let's take a look at the contents of ARRAY.SRC:

We see the content is messy, but we still seem to be able to see a little, such as wangwu/lisi, such as words, that the archive is not in-depth encryption.


2. Solution file

Solution archive NSString *filepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "array.src"];id array = [ Nskeyedunarchiver Unarchiveobjectwithfile:filepath]; NSLog (@ "%@", array);

The solution is also very simple, is to return an object, but this is used in the ID type, because read out is not sure what kind of.

3. Archive multiple objects to a file

The second way//The flaw in the first way is that an object is archived into a file//But the second way, multiple objects can be archived into a file Nsarray *array = [Nsarray arraywithobjects:@ "Zhangsan", @ "Lisi" , nil]; Nsmutabledata *data = [Nsmutabledata data]; Nskeyedarchiver *archiver = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:data]; Encode [archiver encodeobject:array forkey:@ "Array"]; [Archiver encodeint:100 forkey:@ "Scope"]; [Archiver encodeobject:@ "Jack" forkey:@ "name"];  Complete the encoding to populate the above archived data into data, at which time the archived objects are already stored in database [Archiver finishencoding]; [Archiver release];  NSString *filepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "ARRAY.SRC"]; BOOL success = [data Writetofile:filepath atomically:yes]; if (success) {NSLog (@ "Archive succeeded");}

If multiple objects are archived, a class is used here:Nsmutabledata and NSData, the difference between them is simple, one is mutable, and the other is immutable. An archiver is also created here: Nskeyedarchiver, which is responsible for encoding operations of the specified type, and then populates the data into the Nsmutabledata class. When archiving, each type of object is mapped with a key, which is similar to the NSData nsdirctionary.

4, the operation of multiple objects to solve the file

NSString *filepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "ARRAY.SRC"];//read archived data NSData *data = [[NSData] Alloc] initwithcontentsoffile:filepath];//Create a solution archive object, the data in the solution archive nskeyedunarchiver *unarchiver = [[ Nskeyedunarchiver Alloc] initforreadingwithdata:data];//archive Nsarray *array = [unarchiver decodeobjectforkey:@ "Array"] ; NSLog (@ "%@", array); int value = [unarchiver decodeobjectforkey:@ "Scope"]; NSLog (@ "%d", value);

We can unpack the file out of a NSData object, and then we can get the specified type object by key.

Ii. custom type of archive and file

It says that there are existing types of archive and reconciliation files, the following is a look at the custom type of archive and file operations, at the beginning of the same time, if the custom type can be archived and reconciled, you must implement a protocol:nscoding

Not much to say, the following to directly read the code explanation:

Person.h

  person.h//  34_archiveprotocol////  Created by Jiangwei on 14-10-13.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import <foundation/foundation.h>//class only implement nscoding protocol to archive @interface person:nsobject< Nscoding> @property (nonatomic,copy) nsstring *name; @property (nonatomic,assign) Nsinteger age; @property (nonatomic , retain) Nsarray *apples;-(NSString *) description; @end

Here we customize a person type, implement the Nscoding protocol, and then he has three properties, and here we see a new way to define the properties, which is explained in detail later when it comes to memory management.

Person.m

person.m//34_archiveprotocol////Created by Jiangwei on 14-10-13.//Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Person.h" @implementation person//the time of the archive is called//is also an initialization method-(ID) Initwithcoder: (Nscoder *)    adecoder{NSLog (@ "Initwithcoder");    self = [super init];        if (self! = nil) {/* _name = [adecoder decodeobjectforkey:@ "name"];        _age = [Adecoder decodeobjectforkey:@ "age"];         _apples = [Adecoder decodeobjectforkey:@ "apples"];        *///Generally we define the key macro so that there is no error _name = [[Adecoder decodeobjectforkey:@ ' name '] copy];        Self.age = [Adecoder decodeobjectforkey:@ "age"];            Self.apples = [Adecoder decodeobjectforkey:@ "apples"]; } return self;}    This method is called when archiving-(void) Encodewithcoder: (Nscoder *) acoder{NSLog (@ "Encodewithcoder");    [Acoder encodeobject:_name forkey:@ "name"];//the general key and attribute names are taken the same [Acoder encodeinteger:_age forkey:@ "age"]; [Acoder encodeobject:_apples forkey:@ "apples"];}    -(NSString *) description{NSString *string = [NSString stringwithformat:@ "name=%@,age=%d,apples=%@", _name,_age,_apples]; return string;} @end

In the person.m file, we need to implement the two methods in the protocol:

Initwithcoder

Encodewithcoder

The two methods are the one that is called when the archive operation is used, and the one that is called when the action is being used for the file.

1, the method used to solve the document

-(ID) Initwithcoder: (Nscoder *) adecoder{    NSLog (@ "Initwithcoder");    self = [super init];    if (self! = nil) {/        *        _name = [adecoder decodeobjectforkey:@ "name"];        _age = [Adecoder decodeobjectforkey:@ "age"];        _apples = [Adecoder decodeobjectforkey:@ "apples"];         *        ///Generally we define the key macro so that there is no error        _name = [[Adecoder decodeobjectforkey:@ ' name '] copy];        Self.age = [Adecoder decodeobjectforkey:@ "age"];        Self.apples = [Adecoder decodeobjectforkey:@ "apples"];            }    return self;}

This is an initialization method, at the same time, he is also a solution operation will be called method, so here we have to write the initialization method of the specific code, but also write the code of the solution, here the main look at the code of the file

In fact, it is very simple to re-write the value of the property and then assign a key to each property. This is somewhat similar to the parcel in Android.

(Here we see, in the case of the Name property, a copy of the method, which will be said later, there is a shallow copy and deep copy of the points)

2. How to use when filing

This method is called when archiving-(void) Encodewithcoder: (Nscoder *) acoder{    NSLog (@ "Encodewithcoder");    [Acoder encodeobject:_name forkey:@ "name"];//the general key and attribute names are taken the same    [Acoder encodeinteger:_age forkey:@ "age"];    [Acoder encodeobject:_apples forkey:@ "apples"];}

Archiving and reconciling files is the opposite, but note that the key to their attributes must be consistent

3. Overriding the Description method

-(NSString *) description{    nsstring *string = [NSString stringwithformat:@ "name=%@,age=%d,apples=%@", _name,_age, _apples];    return string;}

As I said in the previous article, when we use the NSLog method to print the value of an object, we are actually calling the object's description method, and this method is in the NSObject class, and we can rewrite it so that we can print the information we want. Is the same as the ToString method in Java.

Let's take a look at how it's used.

Main.m

  main.m//  34_archiveprotocol////  Created by Jiangwei on 14-10-13.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import <Foundation/Foundation.h> #import "Person.h" int main (int argc, const char * argv[]) { c4/> @autoreleasepool {person                *p = [[Person alloc] init];        P.name = @ "Zhang San";        P.age =;        P.apples = @[@ "iphone" @ "ipad"];                Archive        NSString *filepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "Person.archiver"];        BOOL success = [Nskeyedarchiver archiverootobject:p tofile:filepath];        if (success) {            NSLog (@ "Archive succeeded");        }                Archive person        *person = [Nskeyedunarchiver Unarchiveobjectwithfile:filepath];        NSLog (@ "%@", person);                    }    return 0;}

As we can see, it is very simple to use and the same way as above, the result of running:

See, our custom description method, print out our own desired results ~ ~

Summarize

In this article, we've talked about the concepts and operations of archiving and documentation in OC, but it's plain to say that objects are written to a file and read from a file.

Archive files for iOS

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.