温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-02 16:43:55 来源:网络 阅读:543 作者:halttt 栏目:开发技术

最近在使用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;
}


改正这样既可。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI