Question

I cannot seem to set a timer output to an NSTextField. I've looked at this Q/A, among many, but must be doing something different but wrong.

I initialize the timer and the textfield in WindowDidLoad.

My timer method is as follows:

time += 1;
        if((time % 60) <= 9) {
            NSString *tempString = [NSString stringWithFormat:@"%d:0%d",(time/60),(time%60)];
            [timerTextField setStringValue:tempString];
        } else {
            NSString *tempString = [NSString stringWithFormat:@"%d:%d",(time/60),(time%60)];
            timerTextField.stringValue = tempString;
        }
        NSLog(@"timerTextField: %@", timerTextField.stringValue);

As you can see, I log the textfield output. I have an IBOutlet connection from the the File's owner to the timerTextField.

I can see the output correctly in the log, but the textfield string is not populated.

Can anyone see anything I'm doing wrong? Thanks

Was it helpful?

Solution

The code you posted looks OK to me. (You could replace it by binding your timerTextField to the time value via Cocoa Bindings though).

How did you create your timer and to which runloop(mode) did you add it? Another problem could be that the outlet to your timerTextField is not connected. Can you set a breakpoint in your timer selector and check if timerTextField is not nil.

Update:

I just tried your code and for me it works.
Given that you have an IBOutlet named timerTextField connected to a NSTextField instance in Interface Builder, this code updates the textfield each second:

@interface SSWAppDelegate ()
{
    NSUInteger time;
}

@property (weak) IBOutlet NSTextField *timerTextField;

@end

@implementation SSWAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSTimer* timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)updateTime:(id)sender
{
    time += 1;
    if((time % 60) <= 9) {
        NSString *tempString = [NSString stringWithFormat:@"%lu:0%lu",(time/60),(time%60)];
        [self.timerTextField setStringValue:tempString];
    } else {
        NSString *tempString = [NSString stringWithFormat:@"%lu:%lu",(time/60),(time%60)];
        self.timerTextField.stringValue = tempString;
    }
    NSLog(@"timerTextField: %@", self.timerTextField.stringValue);
}

@end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top