以编程方式加载 nib2 时,从 nib1 调用 awakeFromNib
当我使用下面的语法从 nib1 加载 nib2 时,我当前的 nib (nib1) 中的 awakeFromNib 方法再次被调用。 (但不是 initWithFrame 方法)即使 nib2 已打开并正确获得焦点。我不希望再次执行 nib1 中的 awakeFromNib 。我想念什么?
[NSBundle loadNibNamed:@"iQueryWindow" owner:self];
更多信息:iQueryWindow.xib 有一个与之关联的 NSView 的 iQueryView.h 和 iQueryView.m 子类,用于创建带有按钮、文本字段等的窗口视图。事件顺序如下所示:我从 nib1 视图中单击了一个按钮,其clicked 事件只有上面一行代码来打开 nib2 的窗口。 Nib2 的窗口打开并进行所有初始化,包括其 (nib2) 自己的 inintWithFrame 和 awakeFromNib 方法。之后,我可以观察到 nib1 的窗口由于其自己的 awakeFromNib 被调用而发生变化(我也可以在 NSlog 语句的帮助下通过控制台观察到这一点)。 (nib2 的窗口显示在 nib1 的顶部。)nib2 上有一个按钮,可以使用以下命令关闭 nib2:[self.window close]。
When I loaded nib2 from nib1 with the syntax below, the awakeFromNib method from my current nib (nib1) got called again. (But not the initWithFrame method) Even though the nib2 was opened and got the focus correctly. I do not want the awakeFromNib from the nib1 to be executed again. What do I miss?
[NSBundle loadNibNamed:@"iQueryWindow" owner:self];
More info: iQueryWindow.xib has a iQueryView.h and iQueryView.m subclass of NSView associated with it to create the window view with button, textfield, etc. The sequence of event looked like this: I clicked a button from nib1 view, its clicked event only has a single line of code as above to open nib2's window. Nib2's window opened with all initialization including inintWithFrame and awakeFromNib methods of its (nib2) own. After that I can observed that nib1's window changed due to its own awakeFromNib got called (I can also observed this via the Console with the help of NSlog statement). (nib2's window displayed on top of nib1's.) There is a button on nib2 that will close nib2 with this: [self.window close].
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
-awakeFromNib
被发送到 nib 文件中的所有对象,包括文件的所有者。如果您有一个从 nib 文件加载的对象,并使该对象成为另一个 nib 文件的所有者,它将收到-awakeFromNib
两次。这是设计造成的。尽管您可以使用 ivar 来管理与从 nib 唤醒有关的类的状态,但请考虑使用 NSViewController 的子类(或 NSWindowController ;目前尚不清楚nib2 有一个视图或窗口作为其顶级对象之一)作为辅助 nib 文件的文件所有者。
-awakeFromNib
is sent to all objects in the nib file, including the file’s owner. If you have an object that’s loaded from a nib file and make that object the owner of another nib file, it’ll receive-awakeFromNib
twice. This happens by design.Although you could have an ivar to manage the state of your class with regard to awakening from nib, consider using a subclass of
NSViewController
(orNSWindowController
; it’s not really clear whether the nib2 has a view or a window as one of its top-level objects) as the file’s owner of the secondary nib file.根据 Bvarious 的建议,我使用 NSWindowController 而不是 NSBundle 来解决此问题。这是代码:
Per Bavarious suggestion, I use NSWindowController instead of NSBundle to resolve this issue. Here is the code: