Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

objective c - Trouble setting label text in iOS

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

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

1 Reply

0 votes
by (71.8m points)

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]];
        });
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...