自定义类归档

自定义类如果需要归档的话,需要遵守NSCoding协议,并实现两个方法:

- (void)encodeWithCoder:(NSCoder *)aCoder;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;

下面以自定义 Person 类为例:

//.h文件
#import <Foundation/Foundation.h>

@interface Person : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSUInteger age;
@end

//.m文件
#import "Person.h"

@implementation Person

/** 
  数据归档调用
    (1)那些属性需要归档
    (2)这些属性如何归档
 */
- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}

/** 
 数据解档调用 
    (1)那些属性需要解档
    (2)如何解档
 */
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    //当父类中又 NSCoding 协议的时候,用[super initWithCoder:aDecoder];
    self = [super init];
    if (self) {
        _name = [aDecoder decodeObjectForKey:@"name"];
        _age = [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}

//类似于java的toString方法
- (NSString *)description{
   return [NSString stringWithFormat:@"name: %@, age: %zd", self.name, self.age];
}

@end

主文件main.m

//初始化自定义类
        Person *person = [[Person alloc] init];
        person.name = @"张三";
        person.age = 20;

        //获取存储路径
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [cachesPath stringByAppendingPathComponent:@"person.data"];
        //数据归档
        [NSKeyedArchiver archiveRootObject:person toFile:filePath];
        //数据解档
        Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        NSLog(@"%@",p);

最终的结果为:
test[8814:79293] name: 张三, age: 20

posted @ 2016-06-20 21:19  zsper  阅读(89)  评论(0编辑  收藏  举报