标签:nscoding协议 ios归档 nskeyedarchiver
使用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- (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/yangbingbingaIOS- NSCoding协议,NSKeyedArchiver自定义类归档使用详解
标签:nscoding协议 ios归档 nskeyedarchiver
原文地址:http://blog.csdn.net/yangbingbinga/article/details/43702941