macos init 和awakeFromNib

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6436895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 08:07:38  来源:igfitidea点击:

init and awakeFromNib

cocoamacos

提问by MatterGoal

I'd like understand why if i try to set value (I.e. setAlphaValue or setTitle) for an object (like a NSButton) in init method nothing happen, but if i call setter function in awakeFromNib it works correctly.

我想了解为什么如果我尝试在 init 方法中为对象(如 NSButton)设置值(即 setAlphaValue 或 setTitle),什么都不会发生,但是如果我在awakeFromNib 中调用 setter 函数,它会正常工作。

@interface appController : NSObject {
    NSButton *btn;
}
@end;

@implementation appController
-(void)awakeFromNib {
   //it works
   [btn setTitle:@"My title"];
}

-(id)init { 
    self = [super init];
    if(self){
        //it doesn't works
        [btn setTitle:@"My title"];
    }
}
@end

回答by

Outlets are set after-initand before-awakeFromNib. If you want to access outlets, you need to do that in -awakeFromNibor another method that's executed after the outlets are set (e.g. -[NSWindowController windowDidLoad]).

出口设置在 之后-init之前-awakeFromNib。如果您想访问插座,您需要在-awakeFromNib设置插座后执行的或另一种方法(例如-[NSWindowController windowDidLoad])。

When a nib file is loaded:

加载 nib 文件时:

  1. Objects in the nib file are allocated/initialised, receiving either -init, -initWithFrame:, or -initWithCoder:
  2. All connections are reestablished. This includes actions, outlets, and bindings.
  3. -awakeFromNibis sent to interface objects, file's owner, and proxy objects.
  1. nib 文件中的对象被分配/初始化,接收-init, -initWithFrame:, 或-initWithCoder:
  2. 重新建立所有连接。这包括操作、出口和绑定。
  3. -awakeFromNib被发送到接口对象、文件所有者和代理对象。

You can read more about the nib loading process in the Resource Programming Guide.

您可以在Resource Programming Guide 中阅读有关笔尖加载过程的更多信息。

回答by Eiko

When in init, the view will not be set up properly, and the outlets aren't connected. That's why you use awakeFromNib:in this case - everything is set up and ready to be used.

在初始化时,视图将无法正确设置,并且插座未连接。这就是您awakeFromNib:在这种情况下使用的原因- 一切都已设置好并可以使用。