使用GCD在后台创建UIKit对象是一种不好的做法吗?

正如bbum 在这里所指出的,文档说:“ 在大多数情况下,UIKit类只应该从应用程序的主线程中使用。对于派生类UIResponder尤其如此,或者涉及在任何应用程序中操作应用程序的用户界面方式。

我以为我理解绘图的方法不能在后台线程中调用,因此创建可以在后台完成,因为只在添加视图时调用drawRect方法。 但也许我错了。

总之,这种代码有风险吗?

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

在此先感谢您的回复!

是的,这很危险。 只有Apple开发人员才能说它有多大风险。

如果文档说“不要使用它”,请不要使用它。

请注意,许多UI对象可以(并且确实)使用共享资源。 如果您在后台线程中使用它们,您将在共享资源上获得竞争条件,并且任何事情都可能发生。