Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel not beeing displaying instantly using thread

I want to load some views in thread to avoid UI freeze waiting loading end.

I'm not used to thread so I make a quick test. My code just try to create views in a thread and add this views in the current viewcontroller view in the main thread.

My UIView is working, but for my UILabel I have to wait between 20-60s to have it on the screen.

I make a test with a UIButton and in this case the button display instantly but the label inside the button display with the same delay than my UILabel.

The only way to have it working as I want is to add a [lbl setNeedsDisplay]; in the main thread to force the UILabel to be displayed instantly. Why? Is it possible to do the job without this line?

    dispatch_queue_t queue = dispatch_queue_create("myqueue", NULL);
dispatch_async(queue, ^{

    // NEW THREAD
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 48)];
    lbl.text = @"FOO";

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    view.backgroundColor = [UIColor redColor];

    // MAIN THREAD
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view addSubview:lbl];
        [lbl setNeedsDisplay]; // Needeed to see the UILabel. WHY???

        [self.view addSubview:view];
    });
});
dispatch_release(queue);
like image 648
Alex Avatar asked Dec 12 '25 09:12

Alex


1 Answers

You should set the text of the label on the main queue as well:

dispatch_async( dispatch_get_main_queue(), ^{
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 48)]
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    lbl.text = @"FOO";
    [self.view addSubview:lbl];
    [self.view addSubview:view];
});

It best to keep all UI stuff on the main queue.

UPDATE:

It appears initWithFrame: is not thread safe (found on the SO answer, see also Threading Considerations in the UIView docs).

like image 55
Mike D Avatar answered Dec 14 '25 05:12

Mike D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!