码迷,mamicode.com
首页 > 其他好文 > 详细

自定义类的归解档

时间:2016-03-22 07:51:54      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

@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);

   

}

 

自定义类的归解档

标签:

原文地址:http://www.cnblogs.com/wujie123/p/5304582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!