NSCoding协议,NSKeyedArchiver自定义类归档使用详解

使用NSCoding协议可以实现归档自定义的类,NSKeyedArchiver可以归档我们自定义的类;要实现自定义类的归档,需要实现

encodeWithCoder(编码)和initWithCoder(解码)

我创建一个自定义的Student类,遵循NSCoding协议,实现这两个方法:

//// Student.h// UserList//// Created by on 14/11/14.// Copyright (c) 2014年 All rights reserved.//#import <Foundation/Foundation.h>@interface Student : NSObject<NSCoding>@property(nonatomic,strong)NSString * name;@property(nonatomic,strong)NSString * age;@end.m文件

//// Student.m// UserList//// Created by yb on 14/11/14.// Copyright (c) 2014年 All rights reserved.//#import "Student.h"@implementation Student- (void)encodeWithCoder:(NSCoder *)aCoder{NSLog(@"%s",__FUNCTION__);[aCoder encodeObject:self.name forKey:@"name"];[aCoder encodeObject:self.age forKey:@"age"];}- (id)initWithCoder:(NSCoder *)aDecoder{NSLog(@"%s",__FUNCTION__);self.name = [aDecoder decodeObjectForKey:@"name"];self.age = [aDecoder decodeObjectForKey:@"age"];return self;}@end我们可以直接在appDelegate中测试一下,如何 归档 和 读取 归档的数据:

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{Student * stu = [[Student alloc]init];stu.name = @"123";stu.age = @"3";NSData * stuD = [NSKeyedArchiver archivedDataWithRootObject:stu];//归档,调用encodeWithCoder方法Student * stu1 = [NSKeyedUnarchiver unarchiveObjectWithData:stuD];//读取归档数据,调用initWithCoderNSLog(@"stu1.name = %@",stu1.name);return YES;}原文地址:

,没有天生的信心,只有不断培养的信心。

NSCoding协议,NSKeyedArchiver自定义类归档使用详解

相关文章:

你感兴趣的文章:

标签云: