Is the creation of an UIKit object in background using GCD a bad practice?

拈花ヽ惹草 提交于 2019-12-24 02:23:34

问题


As pointed out by bbum here, the doc says: "For the most part, UIKit classes should only be used from the main thread of an application This is especially true for derived classes UIResponder or involve the manipulation of user interface of your application in any way. ".

I thought I understood that the methods of drawings could not be called in a background thread, so that the creation could be done in the background, as the drawRect method is only called when the view is added. But maybe i am wrong.

In summary, does that this kind of code is risky?

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);

            dispatch_async(queue, ^{

                NSString *fileName = [pathToModel  stringByAppendingPathComponent:[[compDico valueForKey:@"fileName"] lastPathComponent]];

                UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:
                                                                             fileName]];
                UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 62, 190, 20)];
                [label setText:[[someArray objectAtIndex:i-1] someText]];
                [label setNumberOfLines:0];
                label.font=[UIFont fontWithName:@"arial" size:10.0f];
                [label setBackgroundColor:[UIColor clearColor]];

                // Create some other view here
                // ...

                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.view addSubview:imageView];
                    [self.view addSubview:label];
                    //Add other view here
                    // ...
                });
            });

Thanks for in advance your responses!


回答1:


Yes, this is risky. How risky it is only Apple developers can say.

If the documentation says "don't use it", just don't use it.

Note that many UI objects can (and do) use shared resources. If you use them in a background thread, you'll get a race condition on the shared resource and anything can happen.



来源:https://stackoverflow.com/questions/18476540/is-the-creation-of-an-uikit-object-in-background-using-gcd-a-bad-practice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!