标签:
归档:是对对象及其属性还有同其他对象间的关系进行编码,形成一个文档,该文档既可以保存于文件系统,也可以在进程或网络间传送。
归档过程把对象图保存为一种与架构无关的字节流,保持对象的标识以及对象间的关系。
能够归档的对象必须遵守NSCoding协议,实现以下方法:
- (void)encodeWithCoder:(NSCoder *)aCoder; - (id)initWithCoder:(NSCoder *)aDecoder;
使用NSCoder对象进行编码与解码操作。NSCoder本身是抽象类,实际运行中使用NSKeyedArchiver和NSKeyedUnarchiver这两个具体类,也就是使用基于键的归档技术。
Archiving:
+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;
Unarchiving:
+ (id)unarchiveObjectWithFile:(NSString *)path;
示例:
// // NimoPerson.h // TestDemo // // Created by fu zheng on 15/8/13. // Copyright (c) 2015年 FuZheng. All rights reserved. // #import <Foundation/Foundation.h> @interface NimoPerson : NSObject <NSCoding> @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *gender; @property (nonatomic, assign) NSUInteger age; @property (nonatomic, retain) NSSet *friends; @property (nonatomic, getter = isMarried) BOOL married; @end
// // NimoPerson.m // TestDemo // // Created by fu zheng on 15/8/13. // Copyright (c) 2015年 FuZheng. All rights reserved. // #import "NimoPerson.h" @implementation NimoPerson - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeObject:self.gender forKey:@"gender"]; [aCoder encodeInteger:self.age forKey:@"age"]; [aCoder encodeObject:self.friends forKey:@"friends"]; [aCoder encodeBool:[self isMarried] forKey:@"married"]; } - (id)initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { _name = [[aDecoder decodeObjectForKey:@"name"] copy]; _gender = [[aDecoder decodeObjectForKey:@"gender"] copy]; _age = [aDecoder decodeIntegerForKey:@"age"]; _friends = [aDecoder decodeObjectForKey:@"friends"]; _married = [aDecoder decodeBoolForKey:@"married"]; } return self; } - (id)init { NSSet *friends = [[NSSet alloc] initWithArray:@[@"Tom", @"Jessica", @"Lily"]]; return [self initWithName:@"Tony" gender:@"male" age:28 friends:friends married:NO]; } - (id)initWithName:(NSString *)name gender:(NSString *)gender age:(NSUInteger)age friends:(NSSet *)friends married:(BOOL)married { if (self = [super init]) { _name = [name copy]; _gender = [name copy]; _age = age; _friends = friends; _married = married; } return self; } - (NSString *)description { NSDictionary *desDic = @{@"name":_name, @"gender":_gender, @"age":[NSNumber numberWithInteger:_age], @"married":[NSNumber numberWithBool:_married]}; return [NSString stringWithFormat:@"%@", desDic]; } @end
标签:
原文地址:http://my.oschina.net/fuzheng/blog/491915