标签:ios swift nscoding model 归档
原创blog,转载请注明出处
http://blog.csdn.net/hello_hwc?viewmode=contents
欢迎关注我的iOS SDK详解专栏
http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html
前言:NSCoding是对iOS中的Model类进行编码和解码必须要遵循的协议,如果一个对象要被归档,那么这个协议是必须的。
- initWithCoder: //解码
- encodeWithCoder://编码
一个简单的例子:
OC
@interface MyModel:NSObject<NSCoding>
@property (copy,nonatomic)NSString * name;
@property (nonatomic)int age;
@end
@implementation MyModel
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"kName"];
self.age = [aDecoder decodeInt32ForKey:@"kAge"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"kName"];
[aCoder encodeInt32:self.age forKey:@"kAge"];
}
-(NSString *)description{
return [NSString stringWithFormat:@"Name:%@; Age:%d",self.name,self.age];
}
然后这样调用
[super viewDidLoad];
MyModel * model = [[MyModel alloc] init];
model.name = @"wenchen";
model.age = 24;
NSData * data = [NSKeyedArchiver archivedDataWithRootObject:model];
MyModel * unarchedModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"%@",unarchedModel); //Name:wenchen; Age:24
为什么要写description呢?因为方便调试
Swift实现
class MyModel:NSObject,NSCoding {
var name:String
var age:Int32
init(name:String,age:Int32){
self.name = name
self.age = age
super.init()
}
required init(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObjectForKey("kName") as! String
self.age = aDecoder.decodeIntForKey("kAge")
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.name, forKey: "kName")
aCoder.encodeInt(self.age, forKey: "kAge")
}
}
调用
let model = MyModel(name: "Wenchen", age: 24)
let data = NSKeyedArchiver.archivedDataWithRootObject(model)
let unArchedModel = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! MyModel
println("Name:\(unArchedModel.name); Age:\(unArchedModel.age)")
版权声明:本文为博主原创文章,如需转载请注明出处
标签:ios swift nscoding model 归档
原文地址:http://blog.csdn.net/hello_hwc/article/details/47666695