Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating UI elements in a background thread before being added to a view

I am just trying to wrap my head around Grand Central Dispatch (GCD) and I cant seem to find an answer on this

So I know that in general you aren't supposed to update UIView elements from any thread other than the main thread. So this is illegal:

dispatch_async(workerQueue, ^{
    self.view.backgroundColor = [UIColor redColor];
});

But are you allowed to work on view elements before they are actually added to the view? In other words, is this allowed?

dispatch_async(workerQueue, ^{
    UIButton *thisLevelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    thisLevelButton.frame = CGRectMake(x, y, BUTTON_WIDTH, BUTTON_HEIGHT);
    thisLevelButton.tag = kLevelButtonTags + j;


    int levelState = [[[thisCat objectForKey:[levelNamesInCat objectAtIndex:j]] objectAtIndex:4] intValue];

    [thisLevelButton setBackgroundImage:[UIImage imageNamed:@"ccLSButton50lock"]forState:UIControlStateNormal];
    thisLevelButton.alpha = 0.5;
    [thisLevelButton addTarget:self action:@selector(unlockButtonAction:) forControlEvents:UIControlEventTouchUpInside];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view addSubview:thisLevelButton];
    }

});
like image 354
bkbeachlabs Avatar asked Oct 23 '22 08:10

bkbeachlabs


1 Answers

Yes you can. Best practice is not to update. Initialisation is fine.

An example can be read in this blog post. It is almost on the lines of what you are attempting.

like image 53
Nandeep Mali Avatar answered Oct 27 '22 09:10

Nandeep Mali