UIViewController init 与 initWithNibName:bundle:
在我的应用程序中,我正在推送一个视图控制器(UITableViewController),它还有一个引用 UITableViewCell 的属性/出口。看来,使用以下命令创建控制器
PreferencesController *pController = [[PreferencesController alloc] init];
不会在 xib 文件中创建 UITableViewCell 的对象,因此出口为空,因此表加载会产生异常。 我用以下方法解决了这个问题:
PreferencesController *pController = [[PreferencesController alloc] initWithNibName:@"PreferencesController" bundle:nil];
但我并没有真正明白它为什么起作用,因为从文档来看, init 似乎足以加载相关的 nib 文件(PreferencesController.xib)。
In my app I am pushing a view controller (a UITableViewController) that has also a property/outlet referencing a UITableViewCell. It appears that creating the controller with:
PreferencesController *pController = [[PreferencesController alloc] init];
doesn't create the object for the UITableViewCell in the xib file, thus the outlet is null, thus the table loading generates an exception.
I solved this with:
PreferencesController *pController = [[PreferencesController alloc] initWithNibName:@"PreferencesController" bundle:nil];
but I didn't really get why it worked, as from documentation it seems that init should be sufficient to load the related nib file (PreferencesController.xib).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑:我错了,如果 nib 文件的名称与控制器相同,则它们应该使用
alloc init
自动加载。Interface Builder 中文件的所有者是什么?可以通过更改此值来修改默认行为。
Edit: I was incorrect, nib files should load automatically with
alloc init
if they are named the same as the controller.What is your File's Owner in Interface Builder? The default behavior can be modified by changing this value.
您必须重写
initWithNibName:bundle:
而不是init
因为这是“指定的初始值设定项”。当您从 Nib 文件加载此消息时,这是被调用的创建者消息。资源
You have to override
initWithNibName:bundle:
instead ofinit
because this is the "designated initializer". When you load this from a Nib file, this is the creator message being called.Resources
PreferencesController
这个名字似乎有一些神奇之处。我刚刚遇到了完全相同的问题。将我的类(和 xib)重命名为其他名称解决了问题。There seems to be something magical about the name
PreferencesController
. I just had the exact same problem. Renaming my class (and xib) to something else solved the problem.