码迷,mamicode.com
首页 > 移动开发 > 详细

iOS SDK详解之NSCoding协议

时间:2015-08-14 21:32:18      阅读:354      评论:0      收藏:0      [点我收藏+]

标签: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类进行编码和解码必须要遵循的协议,如果一个对象要被归档,那么这个协议是必须的。


NSCoding要实现两个方法

- initWithCoder: //解码
- encodeWithCoder://编码

一个简单的例子:

  • 定义一个Model,让其遵循NSCoding协议,方便我们进行归档数据存储(直接到plist或者NSUserdefaults)

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 SDK详解之NSCoding协议

标签:ios   swift   nscoding   model   归档   

原文地址:http://blog.csdn.net/hello_hwc/article/details/47666695

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!