归档好比java中的序列化反序列化,即把内存中对象保存到硬盘中,同时可以把硬盘中对象读入内存 自定义类需要实现<NSCoding>协议并实现- (void)encodeWithCoder:(NSCoder *)coder 和 - (id)initWithCoder:(NSCoder *)coder才能被归档, 归档可以自动实现深复制 // // main.m // bundle // // Created by Young on 15/10/12. // Copyright (c) 2015年 Young. All rights reserved. // #import <Foundation/Foundation.h> @interface MyData : NSObject<NSCoding> @property NSString* color; @property double weight; @property int size; @end @implementation MyData - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:_color forKey:@"color"]; [coder encodeDouble:_weight forKey:@"weight"]; [coder encodeInt:_size forKey:@"size"]; } - (id)initWithCoder:(NSCoder *)coder { _color=[coder decodeObjectForKey:@"color"]; _weight=[coder decodeDoubleForKey:@"weight"]; _size=[coder decodeIntForKey:@"size"]; return self; } - (NSString *)description { return [NSString stringWithFormat:@"color=%@, weight=%f, size=%d", _color,_weight,_size]; } @end int main(int argc, const char * argv[]) { @autoreleasepool { /*归档好比java中的序列化反序列化,即把内存中对象保存到硬盘中,同时可以把硬盘中对象读入内存 自定义类需要实现<NSCoding>协议并实现- (void)encodeWithCoder:(NSCoder *)coder 和 - (id)initWithCoder:(NSCoder *)coder才能被归档, */ NSArray* arr=@[@"abc",@"def",@"xyz"]; [NSKeyedArchiver archiveRootObject:arr toFile:@"data.dat"]; NSArray* a=[NSKeyedUnarchiver unarchiveObjectWithFile:@"data.dat"]; NSLog(@"%@",a); MyData*dat=[MyData new]; [dat setColor:@"red"]; [dat setWeight:2.0]; [dat setSize:10]; [NSKeyedArchiver archiveRootObject:dat toFile:@"mydat"]; dat=[NSKeyedUnarchiver unarchiveObjectWithFile:@"mydat"]; NSLog(@"%@",dat); // 可以使用NSData把多个对象一起归档 NSDictionary* dic=@{@"a":@"1" ,@"b":@"2" ,@"c":@"3" }; NSMutableData* mulData=[NSMutableData data]; //用NSMutableData初始化NSKeyedArchiver NSKeyedArchiver* mulKA=[[NSKeyedArchiver alloc]initForWritingWithMutableData:mulData]; [mulKA encodeObject:arr forKey:@"arr"]; [mulKA encodeObject:dic forKey:@"dic"]; [mulKA encodeObject:dat forKey:@"mydata"]; [mulKA encodeObject:@"string..." forKey:@"str"]; //调用finishEncoding完成归档 [mulKA finishEncoding]; //保存到mulData.dat文件中 if ([mulData writeToFile:@"mulData.dat" atomically:YES]==NO) { NSLog(@"归档失败"); }else NSLog(@"归档成功"); ////// //从mulData.dat文件中归档 NSData*data=[NSData dataWithContentsOfFile:@"mulData.dat"]; NSKeyedUnarchiver* nskn=[[NSKeyedUnarchiver alloc]initForReadingWithData:data]; arr=[nskn decodeObjectForKey:@"arr"]; dic=[nskn decodeObjectForKey:@"dic"]; dat=[nskn decodeObjectForKey:@"mydata"]; NSString* s=[nskn decodeObjectForKey:@"str"]; //调用finishDecoding完成归档 [nskn finishDecoding]; NSLog(@"decodeObject %@ \n%@ \n %@ \n %@",arr,dic,dat,s); } return 0; }
打印如下
2015-10-12 12:41:50.765 bundle[1426:101541] ( abc, def, xyz ) 2015-10-12 12:41:50.769 bundle[1426:101541] color=red, weight=2.000000, size=10 2015-10-12 12:41:50.772 bundle[1426:101541] 归档成功 2015-10-12 12:41:50.773 bundle[1426:101541] decodeObject ( abc, def, xyz ) { a = 1; b = 2; c = 3; } color=red, weight=2.000000, size=10 string...