Objective C - loop to change label text

前端 未结 4 1124
礼貌的吻别
礼貌的吻别 2020-11-30 15:08

i have a loop that looks like this

for(int x=0; x < 10; x++){
    [testLabel setText:[self randomString]];
    sleep(1);
}

The randomStr

相关标签:
4条回答
  • 2020-11-30 15:16

    The UI is only updated at the end of a run loop, of which your loop is running inside of a single iteration of. You should be using an NSTimer instead.

    0 讨论(0)
  • 2020-11-30 15:32

    Do not call sleep()

    Certainly not ever on the main thread and any use of sleep in secondary threads is generally highly questionable.

    In this case, just use an NSTimer instance to periodically update the value (as Wilbur said).

    0 讨论(0)
  • 2020-11-30 15:34

    It's better if you run your string on a background thread

    [self performSelectorInBackground:@selector(updateBusyLabel:) withObject:[NSString stringWithFormat:@"Processing ... %i",iteration]];
    
    -(void)updateBusyLabel:(NSString *)busyText {
        [_busyLabel setText:busyText];
    }
    

    I wouldn't use sleep(), and the timer is too much work.

    0 讨论(0)
  • 2020-11-30 15:39

    To get updated you should run it separately:

    for(int x=0; x < 10; x++){
        [self performSelectorOnMainThread:@selector(updateLabel) withObject:nil waitUntilDone:NO];
        sleep(1);
    }
    
    - (void) updateLabel {
        [testLabel setText:[self randomString]];
    }
    
    0 讨论(0)
提交回复
热议问题