关于ios编码解码问题

刚才修改毕设的时候发现了一个问题.

问题产生原因:

我重新创建了一个coredata 的类,里面有一个属性变量是我自定义的类:mapLineInfo

在我调试的时候点击这个按钮,将要把数据存储到数据库中的时候crash了,提示的是reason:[mapLineInfo encodeWithCoder]:unrecognized selector sent to instance xxxx.

百度了一下问题原因    在这里找到了答案

原来是归档自定义对象的时候,系统不知道要如何编码/解码.so it's easy to solve this question now

查询了一下NSCoder 的文档:

The NSCoding protocol declares the two methods that a class must implement so that instances of that class can be encoded and decoded. This capability provides the basis for archiving (where objects and other structures are stored on disk) and distribution (where objects are copied to different address spaces).


NSCoding 协议声明了两个  类中必须实现的方法,通过这两个方法,自定义的类才会被编码,解码.这种特性为实现(对象或者其它结构存储在硬盘上)和分配(对象拷贝到不同的地址空间)提供了基础.

为了保持面向对象的设计原则,一个对象被编码和解码是为了编码和解码他的实例变量.编码器使对象通过引用encodeWithCoder:或者initWithCoder:.

encodeWithCoder 通过编译器提供的方法构造对象来将他的实例变量编码.一个对象可以无限次接受这个构造方法

initWithCoder:从编译器提供的数据中构造一个对象来初始化自己.同样的,它代替其他init方法并且每个对象只调用一次

任何一个对象类应该是可编译的并且适用NSCoding协议和实现自己的方法


下面就来实现吧.


这个是我需要实现编码/解码的类

在.h文件中加入NSCoding代理



.m文件如下

-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.calore forKey:@"calore"];
    [aCoder encodeObject:self.duration forKey:@"duration"];
    [aCoder encodeObject:self.finishTime forKey:@"finishTime"];
    [aCoder encodeObject:self.startTime forKey:@"startTime"];
    [aCoder encodeObject:self.length forKey:@"length"];
    [aCoder encodeObject:self.points forKey:@"points"];
    [aCoder encodeObject:self.tag forKey:@"tag"];
    [aCoder encodeObject:self.weatherInfo forKey:@"weatherInfo"];
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    _calore = [aDecoder decodeObjectForKey:@"calore"];
    _duration = [aDecoder decodeObjectForKey:@"duration"];
    _finishTime = [aDecoder decodeObjectForKey:@"finishTime"];
    _startTime = [aDecoder decodeObjectForKey:@"startTime"];
    _length = [aDecoder decodeObjectForKey:@"length"];
    _points = [aDecoder decodeObjectForKey:@"points"];
    _tag = [aDecoder decodeObjectForKey:@"tag"];
    _weatherInfo = [aDecoder decodeObjectForKey:@"weatherInfo"];
    return self;
}
最后再编译就可以成功运行了.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值