溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

記一次對象歸檔中的錯誤, initWithCoder報

發布時間:2020-08-02 16:43:55 來源:網絡 閱讀:568 作者: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

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女