iOS开发- NSCoding协议,NSKeyedArchiver自定义类归

来源:互联网 发布:上海社会科学院 知乎 编辑:程序博客网 时间:2024/06/11 00:12
使用NSCoding协议可以实现归档自定义的类,NSKeyedArchiver可以归档我们自定义的类;要实现自定义类的归档,需要实现

encodeWithCoder(编码)和initWithCoder(解码)

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

////  Student.h//  UserList////  Created by http://blog.csdn.net/yangbingbinga on 14/11/14.//  Copyright (c) 2014年 http://blog.csdn.net/yangbingbinga. 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年 http://blog.csdn.net/yangbingbinga. 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];//读取归档数据,调用initWithCoder    NSLog(@"stu1.name = %@",stu1.name);    return YES;}
原文地址:http://blog.csdn.net/yangbingbinga


0 0
原创粉丝点击