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.
Recovery archive, English unarchiver, refers to restoring an archived block of data from a file or network to an OC object in memory.
Archiving and recovery is primarily used to store custom type objects, save custom data before a program is paused or closed, and read stored custom data after the program resumes state or starts.
Classes that support archiving and recovery must implement the Nscoding protocol, which is then transformed by the Nskeyedarchiver and Nskeyedunarchiver classes to convert the 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的方式顺序存储和读取的。

Many times we need to archive and restore custom objects, so we need to have custom objects implement the archive function
Implementing an archive requires only following (implementing) the Nscoding protocol or Nscoding sub-protocol.

Nskeyedarchiver

If the object is NSString, Nsdictionary, Nsarray, NSData, NSNumber and other types, you can archive and restore directly with Nskeyedarchiver
Not all objects can be archived directly in this way, only objects that comply with the Nscoding protocol can
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 each 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 NSData, and the NSData is 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 the object
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. Variable data spaces can be created 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];  Start archive object, archived data will be stored in 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-Recovering 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 needs to archive 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 the class that obj needs to archive * @param key Archive key * @param Path Archive Road Strength * * @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

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

iOS development-Data archiving and recovery Nskeyedarchiver

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.