UIKit和GCD线程安全 [英] UIKit and GCD thread-safety

查看:249
本文介绍了UIKit和GCD线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多帖子都说UIKit完全不是线程安全的。现在,在GCD的Apple文档中,我们可以看到它是不是线程安全的DRAWING。所以这样的代码就可以了:

Many of the posts say that UIKit is totally not thread safe. Now on Apple documentation for GCD we can read that it's the DRAWING that is not thread safe. So would code like this be OK :



dispatch_async(^ {

dispatch_async( ^{

//do some work
if(!self.window.rootViewController.presentedViewController && )
    [self.window.rootViewController class] == anotherClass)
  {
      dispatch_async(dispatch_get_main_queue(), ^{  //do some work  });
  }

});



推荐答案

我个人的观点是,到目前为止您所听到的内容具有误导性。

My personal opinion is that what you have heard so far is misleading.

以下是Apple的报价 UIKit框架参考,归功于类似的线程这里

Here is a quote from Apple's UIKit Framework Reference, credit to a similar thread here:


注意:大多数情况下,UIKit类只能用于
应用程序的主要线程。对于从UIResponder派生的类
或者涉及以任何方式操纵
应用程序的用户界面的情况尤其如此。

Note: For the most part, UIKit classes should be used only from an application’s main thread. This is particularly true for classes derived from UIResponder or that involve manipulating your application’s user interface in any way.

另外,请注意,从iOS4开始,与您假设的相反,根据发布在这里的笔记

Also, note, that starting from iOS4, contrary to what you have assumed, according to release notes found here,


在UIKit中绘制图形上下文现在是线程-安全。
具体来说:

Drawing to a graphics context in UIKit is now thread-safe. Specifically:


  • 用于访问和操作图形上下文的例程现在可以正确处理驻留在不同线程上的上下文。

  • 字符串和图像绘制现在是线程安全的。

  • 现在可以安全地使用多个线程中的颜色和字体对象。

事实上,在WWDC 2012会话构建并发用户界面中,Apple工程师演示了绘制到图像后台线程中的图形上下文

In fact furthermore in WWDC 2012 session "Building Concurrent User Interfaces", Apple engineer demonstrates drawing into image graphics context in a background thread.

我的外卖:


  • 您可以使用多线程绘图,但不要假设任何内容。仅使用Apple明确声明的内容。

  • 同样,不要假设。请勿触摸从后台线程继承自 UIResponder 的任何UIKit内容。

  • You can use multi-threaded drawing, but don't assume anything. Use only what is explicitly declared by Apple.
  • Again, assume nothing. Don't touch any of the UIKit stuff that inherits from UIResponder from background thread.

这篇关于UIKit和GCD线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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