NSTextField waits until the end of a loop to update

前端 未结 4 1425
礼貌的吻别
礼貌的吻别 2020-11-27 20:52

Here\'s the problem: I have some code that goes like this

otherWinController = [[NotificationWindowController alloc] init];
for (int i = 0; i < 10; i++)          


        
4条回答
  •  再見小時候
    2020-11-27 21:29

    The problem is that you’re blocking the main thread in your for loop and user interface updates happen on the main thread. The main thread run loop will only spin (and consequently user interface updates will take place) after the method containing that for loop finishes executing.

    If you want to update that text field every second, you should use a timer. For instance, considering otherWinController is an instance variable, declare a counter property in your class and:

    otherWinController = [[NotificationWindowController alloc] init];
    self.counter = 0;
    [otherWinController showMessage:[NSString stringWithFormat:@"%d", self.counter]];
    
    [NSTimer scheduledTimerWithTimeInterval:1.0
                                     target:self
                                   selector:@selector(updateCounter:)
                                   userInfo:nil
                                    repeats:YES];
    

    In the same class, implement the method that’s called whenever the time has been fired:

    - (void)updateCounter:(NSTimer *)timer {
        self.counter = self.counter + 1;
        [otherWinController showMessage:[NSString stringWithFormat:@"%d", self.counter]];
    
        if (self.counter == 9) {
            [timer invalidate];
            // if you want to reset the counter,
            // self.counter = 0;
        }
    }
    

提交回复
热议问题