在添加到视图之前更新后台线程中的UI元素

时间:2012-09-25 19:28:59

标签: iphone objective-c ios multithreading grand-central-dispatch

我只是想绕着Grand Central Dispatch(GCD),我似乎无法找到答案

所以我知道通常你不应该从主线程以外的任何线程更新UIView元素。所以这是非法的:

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

但您是否可以在视图元素实际添加到视图之前处理它们?换句话说,这是允许的吗?

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

});

1 个答案:

答案 0 :(得分:3)

是的,你可以。最佳做法不是更新。初始化很好。

An example can be read in this blog post.这几乎与你所尝试的一致。