Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a connected UILabel

@property (strong, nonatomic) IBOutlet UILabel *label;

And an Action, which is triggered by the button

- (IBAction)buttonPressed:(UIButton *)sender;

When button is pressed, i'd like to update the label to display running seconds up to 3 minutes, so i

- (IBAction)buttonPressed:(UIButton *)sender {
    for (int i =0; i < 180; ++i) {
        [label setText:[NSString stringWithFormat:@"%d", i]];
        sleep(1);
    }
}

Confirmed, method is called, timer is ticking ..the label text however does not change. What am i doing wrong please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
410 views
Welcome To Ask or Share your Answers For Others

1 Answer

The sleep() does not allow the UI thread to update itself.

Here is a sample using GCD that closely matches you original code. Note: there are better ways to do this (see: dispatch_after()).

- (IBAction)buttonPressed:(UIButton *)sender {
    [label setText:[NSString stringWithFormat:@"%d", 0]];

    dispatch_queue_t queue = dispatch_queue_create("com.test.timmer.queue", 0);
    dispatch_async(queue, ^{
    for (int i = 1; i < 180; ++i) {
        sleep(1);
        dispatch_async(dispatch_get_main_queue(), ^{
            [label setText:[NSString stringWithFormat:@"%d", i]];
        });
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...