views:

71

answers:

2

I have an NSSlider (slider) and an NSLabel (label) on a window. I also have a class "Controller" that updates the label whenever the slider's value is changed.

The default position of the slider is 0.5, I'm trying to get is where Controller's constructor updates the label upon program launch.

The following is the implementation file for my attempt to do this. Everything works fine except the label is always 0 when I start the program.

@implementation Controller
{

}

-(id)init
{
    NSLog(@"initializing..."); 
    [self updateLabel];  
    return self;
}

- (IBAction)sliderChanged:(id)sender
{
    [self updateLabel];   
}

- (void)updateLabel
{
    label.text = [NSString stringWithFormat:@"%.1f", slider.value];
}

@end

In the console I see the text "initializing...", but the label is never updated. What am I missing?

A: 

you should achieve this with bindings and without any "glue code" in controllers.

Here's some reference on how to use them: http://cocoadevcentral.com/articles/000080.php

Eimantas
+2  A: 

The controller may be getting initialized (where is your call to [super init]?), but that doesn't mean the outlets are hooked up. The proper way to do that would be to rely on a viewDidLoad, windowDidLoad, or awakeFromNib method.

Dave DeLong
Implementing awakeFromNib did the trick. Thanks! Is that common practice for IB controls?Do I always call [super init] when initializing an object? Is that similar to :base() in C#? I am very new to obj-c!
bufferz
`awakeFromNib` is a method that gets automatically invoked on objects instantiated from a nib file, and is therefore a great place to set up initial values for you UI. As for `[super init]`, check out this question: http://stackoverflow.com/questions/1341734
Dave DeLong