Archive and Nskeyedunarchiver with Nskeyedarichiver

Source: Internet
Author: User

First, the use of archiverootobject for simple archiving

Using Nskeyedarichiver for archiving, nskeyedunarchiver, this way, the data is serialized and deserialized before the data is written and read.

Archive:

    1. NSString *homedictionary = Nshomedirectory (); //Get root directory
    2. NSString *homepath = [homedictionary stringbyappendingpathcomponent:@"Atany.archiver"]; Add a saved file name
    3. BOOL flag = [Nskeyedarchiver archiverootobject:@ "Archive" Tofile:homepath]; //Archive A string

This way you can archive strings, numbers, and so on, as well as Nsarray and nsdictionary. The return value flag indicates whether the archive was successful, yes is successful, and no is a failure.

Pick up file:

    1. [Nskeyedunarchiver Unarchiveobjectwithfile:homepath]

The nskeyedunarchiver is used for the file transfer (deserialization).

There is a drawback to this way of archiving: Only one object can be archived into a file, so how do you archive multiple objects?

II. Archiving of multiple objects

The same is done with Nskeyedarchiver archive, the difference is to archive multiple objects at the same time, here we put an example of a cgpoint point, String, Integer (of course, many types can be, such as uiimage, float, etc.), Use the Encodexxx method to archive and finally write to the file by using the WriteToFile method.

Archive: Write Data

  1. Preparing data
  2. Cgpoint point = Cgpointmake (1.0, 2.0);
  3. NSString *info = @"Origin point of coordinates";
  4. Nsinteger value = 10;
  5. NSString *multihomepath = [Nshomedirectory () stringbyappendingpathcomponent:@"Multi.archiver"];
  6. Nsmutabledata *data = [[Nsmutabledata alloc]init];
  7. Nskeyedarchiver *archvier = [[Nskeyedarchiver alloc]initforwritingwithmutabledata:data];
  8. Archive Multiple Objects
  9. [Archvier encodecgpoint:point forkey:@"Kpoint"];
  10. [Archvier encodeobject:info forkey:@"Kinfo"];
  11. [Archvier encodeinteger:value forkey:@"Kvalue"];
  12. [Archvier finishencoding];
  13. [Data Writetofile:multihomepath Atomically:yes];



Access: Gets the data from the path construct Nskeyedunarchiver instance, using the Decodexxxforkey method to get the object in the file.

    1. Nsmutabledata *datar = [[Nsmutabledata Alloc]initwithcontentsoffile:multihomepath];
    2. Nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc]initforreadingwithdata:dater];
    3. Cgpoint pointr = [unarchiver decodecgpointforkey:@"Kpoint"];
    4. NSString *infor = [unarchiver decodeobjectforkey:@"Kinfo"];
    5. Nsinteger valuer = [unarchiver decodeintegerforkey:@"Kvalue"];
    6. [Unarchiver finishdecoding];
    7. NSLog (@"%f,%f,%@,%d", Pointr.x,pointr.y,infor,valuer);

It can be seen that multiple objects are archived or very convenient, there is a problem here, where the object is the basic type of data, then how to define their own class generated instance object to archive it?

III. Archiving of Custom objects

Custom objects are widely used because they correspond to the model layer in MVC, which is the entity class. In the program, we define a lot of the entity in the model layer, such as user,teacher.

It's much more important to archive your custom objects, because in many cases we need to save the data after the home key and reload it when the program resumes, so archiving is a good choice.

First we need to customize an entity class, Archive.

Archive.h

    1. #import <Foundation/Foundation.h>
    2. @interface Archive:nsobject
    3. @property (copy,nonatomic) NSString *name;
    4. @property Nsinteger age;
    5. @property (copy,nonatomic) NSString *address;
    6. @property (copy,nonatomic) UIImage *photo;
    7. @end

Archive.m

  1. #import "Archive.h"
  2. #define Knamekey @ "Namekey"
  3. #define Kagekey @ "Agekey"
  4. #define Kaddress @ "Addresskey"
  5. #define Kphotokey @ "Photokey"
  6. @implementation Archive
  7. @synthesize name = _name;
  8. @synthesize age = _age;
  9. @synthesize address = _address;
  10. @synthesize photo = _photo;
  11. #pragma mark-nscoding
  12. -(void) Encodewithcoder: (Nscoder *) Acoder {
  13. [Acoder Encodeobject:_name Forkey:knamekey];
  14. [Acoder encodeinteger:_age Forkey:kagekey];
  15. [Acoder encodeobject:_address forkey:kaddress];
  16. [Acoder Encodeobject:_photo Forkey:kphotokey];
  17. }
  18. -(ID) Initwithcoder: (Nscoder *) Adecoder {
  19. if (self = [super init]) {
  20. _name = [Adecoder Decodeobjectforkey:knamekey];
  21. _age = [Adecoder Decodeintegerforkey:kagekey];
  22. _address = [Adecoder decodeobjectforkey:kaddress];
  23. _photo = [Adecoder Decodeobjectforkey:kphotokey];
  24. }
  25. return self;
  26. }
  27. #pragma mark-nscoping
  28. -(ID) Copywithzone: (Nszone *) Zone {
  29. Archive *copy = [[[Self class] allocwithzone:zone] init];
  30. Copy.name = [Self.name copywithzone:zone];
  31. Copy.age = Self.age;
  32. copy.address = [Self.address copywithzone:zone];
  33. Copy.photo = Self.photo;
  34. return copy;
  35. }
  36. @end



The Archive class has four fields (name, age, address, Avatar), except that the age is integer, and everything else is considered an object.

Note: To archive a custom class, each property in the class must be archived, and if it is a type that cannot be archived, we can convert it to nsvalue and then convert it to the appropriate class when it is read.

Archive implements three delegate Method 1) encodewithcoder:2) initwithcoder:3) Copywithzone:

1) Encodewithcoder

Encodes the receiverusing a given archiver

Encodes the message receiver by a given archiver.

The class terminal Encodewithcoder method is called when a encodeobject message is received.

2) Initwithcoder

Returns an objectinitialized from the data in a given unarchiver. (required)

Returns an initialization object from the data of a given unarchiver.

3) Copywithzone

Returnsa new instance that ' s a copy of the receiver

Returns a new instance of a copy of the message receiver.

The concept of the SDK is this, the following look at the specific code of the custom class archive, in fact, and the archive of multiple objects is the same ...

Archive:

  1. Save pictures and Archives
  2. -(Ibaction) Save: (ID) Sender {
  3. //Prepare data
  4. NSString *name = @"Xiao Yang is playing ios";
  5. Nsinteger age = 22;
  6. NSString *address = @"You guess where I am ~";
  7. UIImage *photo = [UIImage imagenamed:@"Loginman.jpg"];
  8. //Store data to class
  9. Archive *archivingdata = [[Archive alloc] init];
  10. Archivingdata.name = name;
  11. Archivingdata.age = age;
  12. archivingdata.address = address;
  13. Archivingdata.photo = photo;
  14. //Archive
  15. Nsmutabledata *data = [[Nsmutabledata alloc] init];
  16. Nskeyedarchiver *archiver = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:data];
  17. [Archiver Encodeobject:archivingdata Forkey:karchivingdatakey]; //Archivingdate's Encodewithcoder
  18. Method is called
  19. [Archiver finishencoding];
  20. //write file
  21. [Data WriteToFile:self.archivingFilePath Atomically:yes];
  22. }

Pick up file:

  1. -(Ibaction) Loadarchive: (ID) Sender {
  2. NSData *data = [[Nsmutabledata alloc] initWithContentsOfFile:self.archivingFilePath];
  3. Nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc] initforreadingwithdata:data];
  4. //Get class
  5. Archive *archivingdata = [Unarchiver Decodeobjectforkey:karchivingdatakey]; //Initwithcoder method is called
  6. [Unarchiver finishdecoding];
  7. //Read the data
  8. NSString *name = archivingdata.name;
  9. Nsinteger age = Archivingdata.age;
  10. NSString *address = archivingdata.address;
  11. Self.imageView.image = Archivingdata.photo;
  12. NSLog (@"%@| | %d| |  %@ ", name,age,address);
  13. }

After we save, we loadarchive once.

The result is:

2013-11-04 19:29:41.743testarchives[16708:c07] Xiao Yang is playing ios| | 22| | Where do you think I am?

Get success.

Archive and Nskeyedunarchiver with Nskeyedarichiver

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.