首页 > 其他 > 详细

记一次对象归档中的错误, initWithCoder报

时间:2015-08-21 17:23:38      阅读:228      评论:0      收藏:0      [点我收藏+]

最近在使用initWithCoder中遇到了野指针的问题;

情形如下:

父类的initwithcoder:

- (id)initWithCoder:(NSCoder *)aDecoder{
    NSDictionary *info = [aDecoder decodeObjectForKey:@"info"];
    self = [[YFModel alloc]initWithInfo:info];
    return self;
}


子类的initithcoder:

- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self){
        _newsTitle = [aDecoder decodeObjectForKey:@"newstitle"];
        _newsDescription = [aDecoder decodeObjectForKey:@"newsDescription"];
        _newsID = [aDecoder decodeObjectForKey:@"newsID"];
        _thumb = [aDecoder decodeObjectForKey:@"thumb"];
        _newsEditor = [aDecoder decodeObjectForKey:@"newsEditro"];
        _newsDetail = [aDecoder decodeObjectForKey:@"newsDetail"];
    }
    return self;
}


调试中出现如下错误:

执行

_newsTitle = [aDecoder decodeObjectForKey:@"newstitle"];

时遇到野指针问题。原因是父类的初始话方法中执行了

self = [[YFModel alloc]initWithInfo:info];

,对内存空间重新分配,子类

self = [super initWithCoder:aDecoder];

得到的指针为父类类型,内存中没有

_newsTitle_newsDescription_newsID_thumb_newsEditor_newsDetail


这些实例变量,所以报错。更改方法,在父类的初始化方法中万万不能alloc

- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    _info = [aDecoder decodeObjectForKey:@"info"];
    return self;
}


改正这样既可。

记一次对象归档中的错误, initWithCoder报

原文:http://10650551.blog.51cto.com/10640551/1686807

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!