【问题标题】:Is the creation of an UIKit object in background using GCD a bad practice?使用 GCD 在后台创建 UIKit 对象是一种不好的做法吗?
【发布时间】:2013-08-27 22:30:50
【问题描述】:

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

我以为我明白绘图的方法不能在后台线程中调用,所以可以在后台进行创建,因为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
                    // ...
                });
            });

提前感谢您的回复!

【问题讨论】:

  • 这里有一些很好的信息:stackoverflow.com/questions/16299842/…
  • 如果记录为不受支持,则不受支持。 巧合 不是可接受的并发方法。它可能在您测试过的情况下“工作”,但在下一次软件更新后失败,在您没有的某些硬件上失败,或者在您从未测试过的某些客户配置上失败。 (感谢您提出明确的问题,顺便说一句)
  • 关于 OP 问题的单独且略微无关的问题。 @bbum 会知道答案,很抱歉在这里发布它,但觉得它不应该有自己的问题。 '0ul' 在创建调度队列时意味着/传达什么意思?
  • @max_ '0ul'(或 '0UL')是 unsigned long 类型的数值常量,其值为零。 dispatch_get_global_queue 的第二个参数当前未使用,因此文档说您应该简单地传递零。
  • @jlehr 感谢您的总结!

标签: ios objective-c cocoa-touch uikit grand-central-dispatch


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-09-09
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多