自定义类的归解档

Posted 原码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义类的归解档相关的知识,希望对你有一定的参考价值。

@interface Student : NSObject

 

@property (strong,nonatomic) NSString *name;

@property (assign,nonatomic) int age;

@property (assign,nonatomic) char sex;

 

-(Student *)initWithDictionary:(NSDictionary *)dic;

 

@end

 

@implementation Student

 

-(Student *)initWithDictionary:(NSDictionary *)dic

{

    self = [super init];

    if (self) {

        self.name = dic[@"name"];

        self.age = [dic[@"age"] intValue];

        self.sex = [dic[@"sex"] charValue];

    }

    return self;

}

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

   

    NSDictionary *dic = @{@"name":@"lisi",@"age":@"30",@"sex":@‘M‘};

    Student *stu = [[Student alloc] initWithDictionary:dic];

    //归档

    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"student.tt"];

    

    NSMutableData *data = [NSMutableData data];

    NSKeyedArchiver *keyArcher = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    [keyArcher encodeObject:stu.name forKey:@"name"];

    [keyArcher encodeInt:stu.age forKey:@"age"];

    [keyArcher encodeInt:stu.sex forKey:@"sex"];

    

    [keyArcher finishEncoding];

    BOOL bol = [data writeToFile:path atomically:YES];

    NSLog(@"%d",bol);

    NSLog(@"%@",path);

    

    

    

    //解档

    

    NSData *data1 = [NSData dataWithContentsOfFile:path];

    NSKeyedUnarchiver *keyUn = [[NSKeyedUnarchiver alloc] initForReadingWithData:data1];

    

    NSString *name = [keyUn decodeObjectForKey:@"name"];

    int age = [keyUn decodeIntForKey:@"age"];

    char sex = [keyUn decodeIntForKey:@"sex"];

    

    NSLog(@"name = %@,age = %d,sex = ‘%c‘",name,age,sex);

   

}

 

以上是关于自定义类的归解档的主要内容,如果未能解决你的问题,请参考以下文章

第六十三篇runtime实现归解档

聚类分析——层次聚类

NSKeyedUnarchiver归档

一.数据的存储方式

用runtime来重写Coder和deCode方法 归档解档的时候使用

来自自定义类的 Swift addChild