16

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.

@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
MatterGoal
  • 16,038
  • 19
  • 109
  • 186

2 Answers2

46

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

When a nib file is loaded:

  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. -awakeFromNib is sent to interface objects, file’s owner, and proxy objects.

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

  • Thank you! perfect answer (i need wait some more minutes to accept it :)) – MatterGoal Jun 22 '11 at 08:32
  • 3
    I would like to add this: "The order in which the nib-loading code calls the awakeFromNib methods of objects is not guaranteed. In OS X, Cocoa tries to call the awakeFromNib method of File’s Owner last but does not guarantee that behavior. If you need to configure the objects in your nib file further at load time, the most appropriate time to do so is after your nib-loading call returns. At that point, all of the objects are created, initialized, and ready for use." from Resource Programming Guide in this answer. – Helin Wang Feb 13 '13 at 02:32
5

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.

Eiko
  • 25,601
  • 15
  • 56
  • 71