IOS- 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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。