使用GCD在后台创建UIKit对象是一种不好的做法吗? [英] Is the creation of an UIKit object in background using GCD a bad practice?

查看:65
本文介绍了使用GCD在后台创建UIKit对象是一种不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bbum 指出的 此处,文档中
表示: 在大多数情况下,UIKit类只能在应用程序的主线程中使用。对于派生类UIResponder或涉及操纵,尤其如此

我以为我知道不能在后台线程中调用绘图方法,所以可以在后台完成创建,因为只有在添加视图时才调用drawRect方法。但是也许我错了。

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
                    // ...
                });
            });

感谢您的提前答复!

推荐答案

是的,这是有风险的。

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.

请注意,许多UI对象可以(并且确实)使用共享资源。如果您在后台线程中使用它们,则会在共享资源上出现争用条件,一切都会发生。

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.

这篇关于使用GCD在后台创建UIKit对象是一种不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆