Choops
Choops

Reputation: 75

TextField will not update in Cocoa application

I am creating a simple countdown application in Cocoa. When I click the "Start Countdown" button, I get the spinning mouse indicator. After the correct amount of time (for example, if "2" was put in the box, the application would wait 2 seconds), the TextField skips right to 0. Here is my code:

#import "APPAppDelegate.h"

@implementation APPAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
}

- (IBAction)StartCountdown:(id)sender {
    int counterNow, counterLater;
    counterNow = [_FieldCount intValue];
    while (counterNow>1){
        counterNow = [_FieldCount intValue];
        counterLater = counterNow - 1;
        [NSThread sleepForTimeInterval:1.0f];
        [_FieldCount setIntValue:counterLater];
    }
}
@end

Upvotes: 0

Views: 56

Answers (1)

user1118321
user1118321

Reputation: 26365

You need to let the run loop run in order for updates to make it to the screen. You're changing the value, then sleeping the thread. A better method would be to have an NSTimer which sets the text of the text field, and then calls -setNeedsDisplay:YES on it. Something like this:

-(void)fireTimer:(NSTimer*)timer
{
    counterNow = [_FieldCount intValue];
    counterNow--;
    [_FieldCount setIntValue:counterNow];
}

This assumes that _FieldCount is an NSTextField. You'd set this up by creating a repeating timer. If you wanted it to repeat once per second, you could do the following:

NSTimer* secondsTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fireTimer:) userInfo:nil repeats:YES];

Upvotes: 1

Related Questions