对于上一章节,简单讲述了一个自定义对象的归档与解归档:http://www.cnblogs.com/BeyondAverage0908/p/4597245.html
本章节阐述下多个自定义对象的归档与解归档
以下代码阐述:定义了两个类Dog和Cat,并且利用@property展开了对应的几个属性(简单的代码,不贴源码了)。
以下代码部分位主要的归档与解归档代码:注意需要在对应的自定义类中实现以下两个方法:- (void)encodeWithCoder:(NSCoder *)aCoder;方法,- (id)initWithCoder:(NSCoder *)aDecoder; 具体的实现详情见上一篇博客内容
#import "Dog.h" #import "Cat.h" int main(int argc, const char * argv[]) { @autoreleasepool { //定义Dog对象 Dog *xiaohei = [[Dog alloc] init]; xiaohei.name = @"小黑"; xiaohei.age = 12; Cat *xiaomao = [[Cat alloc] init]; xiaomao.name = @"小猫"; xiaomao.nickname = @"阿花"; xiaomao.weight = 2.03; //归档 //定义一个可变数据对象(必须),在编码的时候存储自定义对象 NSMutableData *mutDate = [NSMutableData data]; NSKeyedArchiver *keyedArch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutDate]; //对 dog 和 cat 进行格式编码 [keyedArch encodeObject:xiaohei forKey:@"xiaohei"]; [keyedArch encodeObject:xiaomao forKey:@"xiaomao"]; //结束编码 [keyedArch finishEncoding]; BOOL flag = [mutDate writeToFile:@"/Users/qianfeng/Desktop/day22_OC12_协议/day22_OC12_自定义对象归档与解归档/dogandcat.txt" atomically:YES]; if (flag) { NSLog(@"多个自定义对象归档成功"); }else{ NSLog(@"多个自定义对象归档失败"); } //解归档:将归档后的文件中的对象读取出来 NSData *data = [NSData dataWithContentsOfFile:@"/Users/qianfeng/Desktop/day22_OC12_协议/day22_OC12_自定义对象归档与解归档/dogandcat.txt"]; NSKeyedUnarchiver *keyedUnarch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; Dog *nDog = [keyedUnarch decodeObjectForKey:@"xiaohei"]; Cat *nCat = [keyedUnarch decodeObjectForKey:@"xiaomao"]; [keyedUnarch finishDecoding]; NSLog(@"nDog = %@",nDog); NSLog(@"nCat name = %@,nickname = %@,weight = %.2f",nCat.name,nCat.nickname,nCat.weight); } return 0; }
时间: 2024-10-15 18:58:46