IOS-archive and Archiver, UnArchiver, and ios-unarchiver

Source: Internet
Author: User

IOS-archive and Archiver, UnArchiver, and ios-unarchiver

1. Existing archive and archive

First, let's look at a simple example:

// Method 1: Archive object // object --> file NSArray * array = [NSArray arrayWithObjects: @ "zhang", @ "wangwu", @ "lisi", nil]; // NSHomeDirectory get the root directory stringByAppendingPathComponent Add the stored file name NSString * filePath = [NSHomeDirectory () stringByAppendingPathComponent: @ "array. src "]; BOOL success = [NSKeyedArchiver archiveRootObject: array toFile: filePath]; if (success) {NSLog (@" saved successfully ");} else {NSLog (@ "not saved");} // unarchive array = [NSKeyedUnarchiver unarchiveObjectWithFile: filePath]; NSLog (@ "% @", array );

// Method 2

// The first method is to archive an object into an object.

// But in the second method, multiple objects can be archived into one file.

NSArray * array = [NSArray arrayWithObjects: @ "zhangsan", @ "lisi", nil];

NSMutableData * data = [NSMutableData data];

NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: data];

// Encoding

[Archiver encodeObject: array forKey: @ "array"];

[Archiver encodeInt: 100 forKey: @ "scope"];

[Archiver encodeObject: @ "jack" forKey: @ "name"];

// Complete the encoding and fill the above archive data into the data. At this time, the data of the archive object has been stored in the data.

[Archiver finishEncoding];

NSString * filePath = [NSHomeDirectory () stringByAppendingPathComponent: @ "array. src"];

BOOL success = [data writeToFile: filePath atomically: YES];

If (success ){

NSLog (@ "ARCHIVE successful ");

}

 

// Unarchive multiple objects

/*

NSString * filePath = [NSHomeDirectory () stringByAppendingPathComponent: @ "array. src"];

// Read archive data

NSData * data = [[NSData alloc] initWithContentsOfFile: filePath];

// Create an archive object to archive data

NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: data];

// Archive

NSArray * array = [unarchiver decodeObjectForKey: @ "array"];

NSLog (@ "% @", array );

Int value = (int) [unarchiver decodeObjectForKey: @ "scope"];

NSLog (@ "% d", value );

*/

  • Archive the following code to write an NSArray object to a file.
// Object --> file NSArray * array = [NSArray arrayWithObjects: @ "zhang", @ "wangwu", @ "lisi", nil]; // NSHomeDirectory get the root directory stringByAppendingPathComponent Add the stored file name NSString * filePath = [NSHomeDirectory () stringByAppendingPathComponent: @ "array. src "]; BOOL success = [NSKeyedArchiver archiveRootObject: array toFile: filePath]; if (success) {NSLog (@" saved successfully ");} else {NSLog (@ "not saved ");

The following code creates a file:

NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.src"];
  • The code below shows that the archive is to return an object.
array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];     NSLog(@"%@",array);
  • Archive multiple objects to one file
// The second method // The first method is to archive an object into a file // but the second method, multiple objects can be archived into a file NSArray * array = [NSArray arrayWithObjects: @ "zhangsan", @ "lisi", nil]; NSMutableData * data = [NSMutableData data]; NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] encoding: data]; // code [archiver encodeObject: array forKey: @ "array"]; [archiver encodeInt: 100 forKey: @ "scope"]; [archiver encodeObject: @ "jack" forKey: @ "name"]; // complete the encoding and fill in the archived data to the data, in this case, [archiver finishEncoding]; NSString * filePath = [NSHomeDirectory () stringByAppendingPathComponent: @ "array. src "]; BOOL success = [data writeToFile: filePath atomically: YES]; if (success) {NSLog (@" ");}

If multiple objects are archived, a class is used here:NSMutableData and NSDataThe difference between them is very simple. One is variable, and the other is immutable. Then, an archive: NSKeyedArchiver is created. This class is responsible for encoding of the specified type, and then fills the data into the NSMutableData class. Each type of object is matched with a key during archiving. This NSData is similar to NSDirctionary.

  • Unarchive multiple objects
NSString * filePath = [NSHomeDirectory () stringByAppendingPathComponent: @ "array. src "]; // read the archived data NSData * data = [[NSData alloc] initWithContentsOfFile: filePath]; // create an archive object, unarchive the data in data * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: data]; // unarchive NSArray * array = [unarchiver decodeObjectForKey: @ "array"]; NSLog (@ "% @", array); int value = (int) [unarchiver decodeObjectForKey: @ "scope"]; NSLog (@ "% d", value );

We can archive the file to an NSData object, and then get the specified type object through the key.

 

Ii. Custom archive and archive

The existing types of archive and archive files are mentioned above. Let's take a look at the custom types of archive and archive operations. At the beginning, we also said, if the custom type can be archived and archived, a protocol must be implemented:NSCoding

Student. h

 

# Import <Foundation/Foundation. h> // the class can be archived only when the NSCoding protocol is implemented @ interface Student: NSObject <NSCoding> @ property (copy, nonatomic) NSString * name; @ property (assign, nonatomic) int age; @ property (strong, nonatomic) NSString * adder; @ end

Here we have customized a Student type and implemented the NSCoding protocol. Then there are three attributes. here we can see a new method to define attributes.

Student. m

# Import "Student. h "@ implementation Student // calling during archiving is also an initialization-(instancetype) initWithCoder :( NSCoder *) aDecoder {NSLog (@" initWithCoder "); self = [super init]; if (self! = Nil) {// generally, the key is defined as a macro, so that no error occurs. _ name = [[aDecoder decodeObjectForKey: @ "name"] copy]; self. age = (int) [aDecoder decodeIntegerForKey: @ "age"]; _ adder = [aDecoder decodeObjectForKey: @ "adder"];} return self ;} // call this method during archiving-(void) encodeWithCoder :( NSCoder *) acder {NSLog (@ "encodeWithCoder"); [ACO encodeObject: _ name forKey: @ "name"]; // generally, the key and attribute names are the same [acder encodeInteger: _ age forKey: @ "age"]; [acder encodeObject: _ adder forKey: @ "adder"];} // description method-(NSString *) description {return [NSString stringWithFormat: @ "name = % @, age = % d, adder = % @", _ name, _ age, _ adder] ;}@ end

In the Person. m file, we need to implement two methods in the Protocol:

InitWithCoder

EncodeWithCoder

One of the two methods is called when archiving operations are performed, and the other is called when the archive operation is performed.

1. Methods used for file Decoding

-(Instancetype) initWithCoder :( NSCoder *) aDecoder {NSLog (@ "initWithCoder"); self = [super init]; if (self! = Nil) {// generally, the key is defined as a macro, so that no error occurs. _ name = [[aDecoder decodeObjectForKey: @ "name"] copy]; self. age = (int) [aDecoder decodeIntegerForKey: @ "age"]; _ adder = [aDecoder decodeObjectForKey: @ "adder"];} return self ;}

This is an initialization method, and it is also a method called during the archive operation. Therefore, we need to write the specific code of the initialization method here, you also need to write the code for the archive. Here we mainly look at the code for the archive.

In fact, it is very easy to re-write the value of the attribute, and then specify a key for each attribute.

 

2. Methods used for archiving

// Call this method during archiving-(void) encodeWithCoder :( NSCoder *) acder {NSLog (@ "encodeWithCoder"); [ACO encodeObject: _ name forKey: @ "name"]; // generally, the key and attribute names are the same [acder encodeInteger: _ age forKey: @ "age"]; [acder encodeObject: _ adder forKey: @ "adder"];}

The archive and archive operations are the opposite, but note that the keys of their attributes must be consistent.

 3. Rewrite the description method.

- (NSString *)description{    return [NSString stringWithFormat:@"name=%@,age=%d,adder=%@", _name,_age,_adder];}

As I mentioned in my previous article, when we use the NSLog method to print the object value, we actually call the description method of the object, which is in the NSObject class, we can rewrite it so that we can print the information we want. Same as the toString method in Java.

 

Next let's take a look at the usage.

# Import "ViewController. h "@ interface ViewController () @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; Student * stu = [Student new]; stu. name = @ "Zhang San"; stu. age = 12; stu. adder = @ "Beijing"; // archive NSString * filePath = [NSHomeDirectory () stringByAppendingPathComponent: @ "message. plist "]; NSLog (@" % @ ", filePath); BOOL bol = [NSKeyedArchiver archiveRootObject: stu toFile: filePath]; if (bol) {NSLog (@ "" ");} else {NSLog (@" ");} // unarchive Student * stu1 = [NSKeyedUnarchiver unarchiveObjectWithFile: filePath]; NSLog (@ "% @", stu1);}-(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end

We can see that it is very simple to use and the above method, the running result:

The custom description method prints the desired result ~~

 

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.