initWithCoder:被 nib & 调用NS编码!
好吧,我现在在尝试让 initWithCoder: 正常工作时遇到很多问题。我有一个已加载的 nib 文件,在我的应用程序委托中,我为与该 nib 关联的视图控制器调用 unarchiveWithFile: ,现在我的应用程序崩溃了。我可以看到 initWithCoder: 被调用两次,大概是从 awakeFromNib: 被调用时调用一次,然后是从我调用 unarchiveWithFile: 时调用一次,因为视图控制器符合 NSCoding。但现在要么在视图加载时要么在我按下 IBOutlet 时崩溃。有什么建议吗??
编辑:这是 initWithCoder 的代码:
- (id)initWithCoder:(NSCoder *)coder {
[super initWithCoder:coder];
[[self mapView] addAnnotations:[[coder decodeObjectForKey:@"Annotations"] retain]];
return self;
}
我所做的就是解码地图视图的注释数组,但是在该方法的某个地方被调用两次,然后崩溃。
Ok, I'm having a lot of problems right now trying to get initWithCoder: to work right. I have a nib file that gets loaded, and in my app delegate, I call unarchiveWithFile: for the view controller that is associated with that nib, and now my app crashes. I can see that initWithCoder: is being called twice, presumably once from when awakeFromNib: is called, and then from when I call unarchiveWithFile: since the view controller conforms to NSCoding. But now either it crashes as soon as the view loads or when I press an IBOutlet. Any suggestions??
Edit: Here's the code for initWithCoder:
- (id)initWithCoder:(NSCoder *)coder {
[super initWithCoder:coder];
[[self mapView] addAnnotations:[[coder decodeObjectForKey:@"Annotations"] retain]];
return self;
}
All I'm doing is decoding an array of annotations for a map view, but somewhere along the line this method is being called twice and then it crashes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要忘记将 nil 检查放入 init 方法中。 那么您发布的方法会更正确
例如,如果您将其写为:但这不是问题的原因,
。您自己取消归档视图控制器是否有充分的理由?如果你不做任何特别的事情,你可以依靠现有的机制来完成。 UIViewController 的 init 的默认实现会查找与视图控制器同名的 nib,如果存在,则会加载该 nib(通过 initWithNibName)。
如果您需要归档和归档某些数据,那么它可能实际上不应该是 UIViewController 的一部分。也许在其他地方把它分解出来?
Don't forget to put the nil check in your init methods. E.g. the method you posted would be more correct if you wrote it as:
That's not the cause of your problem, however.
Is there are good reason for you unarchiving your view controller yourself? If you're not doing anything special, you can rely on the existing mechanisms to do it. The default implementation of init for a UIViewController looks for a nib with the same name as your view controller, and if it exists, it loads the nib (via initWithNibName).
If there is data which you need to archive in and out, it may be that it shouldn't be actually part of the UIViewController. Factor it out elsewhere perhaps?
你可以尝试
you can try