最近在使用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; }
改正這樣既可。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。