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

情形如下:

父类的initwithcoder:

-(id)initWithCoder:(NSCoder*)aDecoder{NSDictionary*info=[aDecoderdecodeObjectForKey:@"info"];self=[[YFModelalloc]initWithInfo:info];returnself;}


子类的initithcoder:

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


调试中出现如下错误:

执行

_newsTitle=[aDecoderdecodeObjectForKey:@"newstitle"];

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

self=[[YFModelalloc]initWithInfo:info];

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

self=[superinitWithCoder:aDecoder];

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

_newsTitle_newsDescription_newsID_thumb_newsEditor_newsDetail


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

-(id)initWithCoder:(NSCoder*)aDecoder{self=[superinit];_info=[aDecoderdecodeObjectForKey:@"info"];returnself;}


改正这样既可。