iOS development-Data archiving and recovery Nskeyedarchiver

Source: Internet
Author: User

Archiving and recovery archiving

Archive, English archiver[' ɑrk?v?], this refers to storing OC objects as a file or a block of data on the network.
Recover the archive. English unarchiver refers to the restoration of an archived block of data from a file or network to an OC object in memory.


Archiving and recovery are primarily used to store your own defined type objects. Save your own definition data before the program pauses or shuts down. Reads the stored self-defined data after the program resumes state or starts again.
Classes that support archiving and recovery must implement the Nscoding protocol, which is then transformed by the Nskeyedarchiver and Nskeyedunarchiver classes. Convert an object to a data stream
Other languages, such as Java/.net, refer to this technique as serialization.

Archive collection Types
IOS 非常多内置类型都默认实现了归档功能。如NSNumber,NSArray,NSDictionary,NSString,NSData等。定义NSArray或NSDicitionary类型,初始化数据后。调用NSKeyedArchiver 类的archiveRootObject 传入file路径,就可以将当前NSArray对象完善的保存到文件系统中。

读取归档数据,使用NSKeydUnarchiver类unarchiveObjectWithFile方法能够直接从文件读回数据,并返回NSArray对象NSKeyedArchiver和NSKeyedUnarchiver类都是将对象属性和值以key|value的方式顺序存储和读取的。

Very often we need to archive and restore our own definition objects, so we need to define our own objects to implement the archive function
Implementing an archive requires only following (implementing) Nscoding protocols or nscoding sub-protocols.

Nskeyedarchiver

Assume that the objects are NSString, Nsdictionary, Nsarray, NSData, NSNumber, etc., and can be archived and restored directly with Nskeyedarchiver
Not all objects can be archived directly in such a way that only the objects that have complied with the Nscoding protocol are capable of
There are 2 ways to nscoding a protocol:
Encodewithcoder:
This method is called every time the object is archived.

In this method, you typically specify how to archive every instance variable in an object, and you can use the Encodeobject:forkey: method to archive instance variables
Initwithcoder:
This method is called every time the object is recovered (decoded) from the file.

In this method, you typically specify how to decode the data in a file as an instance variable of an object, and you can use the Decodeobject:forkey method to decode the instance variable

Sometimes it is necessary to archive multiple objects to a file, at which point we need to use Nsmutabledata as the buffer storage object.


The object is archived to the NSData first. The NSData is then written to the file.

nskeyedarchiver-Archive Nsarray
归档一个NSArray对象到Documents/array.archiveNSArray *array = [NSArray arrayWithObjects:@”a”,@”b”,nil];[NSKeyedArchiver archiveRootObject:array toFile:path];
恢复(解码)NSArray对象NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path]
nskeyedarchiver-Archive Person Object (Person.h)
@interface Person : NSObject<NSCoding>@property (nonatomicNSString *name;@property (nonatomicassignint age;@property (nonatomicassignfloat height;@end
nskeyedarchiver-Archive Person Object (PERSON.M)
 @implementation   person- (void) Encodewithcoder: (Nscoder *) encoder {[Encoder encodeobject: Self. Nameforkey:@"Name"]; [Encoder Encodeint: Self. Ageforkey:@"Age"]; [Encoder encodefloat: Self. Heightforkey:@"Height"];} - (ID) Initwithcoder: (Nscoder *) Decoder { Self. Name= [Decoder decodeobjectforkey:@"Name"]; Self. Age= [Decoder decodeintforkey:@"Age"]; Self. Height= [Decoder decodefloatforkey:@"Height"];return  Self;} - (void) Dealloc {[SuperDealloc]; [_name release];}@end
nskeyedarchiver-Archive person Objects (encoding and decoding)
//归档(编码)Person *person = [[[Person alloc] init] autorelease];person.name = @"wangzhaolu";person.age26;person.height1.78f;[NSKeyedArchiver archiveRootObject:person toFile:path];//恢复(解码)Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
Note for nskeyedarchiver-archived objects
假设父类也遵守了NSCoding协议,请注意:应该在encodeWithCoder:方法中加上一句[superencodeWithCode:encode];确保继承的实例变量也能被编码,即也能被归档应该在initWithCoder:方法中加上一句self = [superinitWithCoder:decoder];确保继承的实例变量也能被解码。即也能被恢复
NSData

Use the Archiverootobject:tofile: method to write an object directly to a file, but sometimes you might want to write multiple objects to the same file, then use NSData to archive objects
NSData can provide temporary storage for some data for subsequent writing to a file, or for storing the contents of a file read from disk.

Ability to create variable data spaces using [Nsmutabledata data]

nsdata-Archive 2 person objects into the same file
//Archive (Encode)//Create a new variable data area nsmutabledata  * data  = [nsmutabledata  data ];  Connect the data area to a nskeyedarchiver  object nskeyedarchiver  * Archiver = [[[nskeyedarchiver  alloc] Initforwritingwithmutabledata:data ] autorelease];  When you start archiving objects, the archived data is stored in the nsmutabledata  [archiver encodeobject:person1 Forkey:@ "Person1" ]; [Archiver encodeobject:person2 forkey:@ "Person2" ];//archive Complete (be sure to call this method) [Archiver finishencoding];//writing archived data to a file [data  Writetofile:path Atomically:yes ];  
nsdata-Recover 2 person objects from the same file
恢复(解码)// 从文件里读取数据NSData *data = [NSData dataWithContentsOfFile:path];// 依据数据,解析成一个NSKeyedUnarchiver对象NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];Person *person1 = [unarchiver decodeObjectForKey:@"person1"];Person *person2 = [unarchiver decodeObjectForKey:@"person2"];// 恢复完成[unarchiver finishDecoding];
Archived Packages
 #import <Foundation/ Foundation.h>    @interface  nsobject  (addition )  + ( BOOL ) Keyedarchiver: (id ) obj key: (nsstring  *) key;+ (bool ) Keyedarchiver: (id ) obj Key: (nsstring  *) Key path: (nsstring  *) path;+ (id ) Keyedunarchiver: (nsstring  *) key;+ ( Span class= "Hljs-keyword" >id ) Keyedunarchiver: (nsstring  *) Key path: ( Span class= "hljs-built_in" >nsstring  *) path;  @end  
#define Defaultkeyedarchiverpath [NSString stringwithformat:@"%@/documents/defaultkeyedarchiver.data", Nshomedirectory ()]@implementationNSObject (addition)/** * Archive * * @param obj Required class * @param Key Archive Key * * @return Yes for success, no for failure */+ (BOOL) Keyedarchiver: (ID) obj key: (NSString *) key{return[Self keyedarchiver:obj key:key path:defaultkeyedarchiverpath];}/** * Archive * * @param obj Required class * @param key Archive key * @param Path Archive path * * @return Yes indicates the archive was successful, no indicates an archive failure * /+ (BOOL) Keyedarchiver: (ID) obj key: (NSString *) Key path: (NSString *) path{nsmutabledata *tpdata = [Nsmutabledata data];    Nskeyedarchiver *keyedarchiver = [[Nskeyedarchiver alloc]initforwritingwithmutabledata:tpdata];    [Keyedarchiver encodeobject:obj Forkey:key]; [Keyedarchiver finishencoding];return[Tpdata Writetofile:path atomically:yes];}/** * * * * * * @param Key Key * * @return Results of resolution */+ (ID) keyedunarchiver: (NSString *) key{return[Self Keyedunarchiver:key path:defaultkeyedarchiverpath];}/** * * * * @param key to unlock key * @param Path PATH * * * @return Results of resolution */+ (ID) keyedunarchiver: (NSString *) Key path: (NSString *) path{nsmutabledata *tpdata = [Nsmutabledata datawithcontentsoff    Ile:path]; Nskeyedunarchiver *keyedunarchiver = [[Nskeyedunarchiver alloc]initforreadingwithdata:tpdata];return[Keyedunarchiver Decodeobjectforkey:key];}@end

iOS development-Data archiving and recovery Nskeyedarchiver

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.