遵循NSCoding协议的类可以被序列化和反序列化。
实现两个方法: -initWithCoder: 和 encodeWithCoder:。
新建Person类,实现协议方法
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding> // 遵守NSCoding协议
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
#import "Person.h"
@implementation Model
// 实现归档归档
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
[aDecoder encodeObject:self.name forKey:@"name"];
[aDecoder encodeObject:self.age forKey:@"age"];
}
return self;
}
// 实现解档
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder decodeObjectForKey:"name"];
[aCoder decodeObjectForKey:@"age"];
}
开始归档
// 归档地址
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)] firstObject];
NSString *fullPath = [path stringByAppendingPathComponent:path];
// 需要归档的对象
Person *p = [Person alloc] init];
p.name = @"apple";
p.age = 12;
// 开始归档
BOOL success = [NSKeyedArchiver archiveRootObject:p toFile:fullPath];
//这两句等于上面一句
// NSData *data = [NSKeyedArchiver archivedDataWithRootObject:p];
// [data writeToFile:fullPath atomically:YES];
if (success) {
NSLog(@"归档成功");
} else {
NSLog(@"归档失败");
}
// 解档
Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:fullPath];
网友评论