什么需要在主线程? [英] What Needs To Be on Main Thread?

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

问题描述

我写了一个名为 ensureInMainThread 的小定义(我使用它很多)。但是,我不确定在主线程上确切调用哪些用户界面方法需要。那么 setNeedsDisplay setNeedsLayout 呢?在iOS 5.x中需要在主线程上调用的方法的经验法则是什么?

I have written a little define called ensureInMainThread (and I use it quite a bit). However, I'm not sure exactly which user interface methods require being called on the main thread. What about setNeedsDisplay and setNeedsLayout? What is the rule of thumb for methods that need to be called on the main thread in iOS 5.x?

这些问题是相关的(一些低质量的问题和答案,和一些非常具体的案例),但我想要一个全面,单一的好答案:

These questions are related (some low quality questions and answers, and some very case specific), but I would like a comprehensive, single good answer:

  • UIView setNeedsDisplay Not on main thread?
  • Does UIView's -drawRect: have to be called on the main thread?
  • Make UIImage From UIView but NOT in the main thread

推荐答案

自iOS 4.0起,可以在后台线程上执行某些用户界面更新

As of iOS 4.0, some user interface updates can be performed on a background thread:



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

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


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

  • The routines used to access and manipulate the graphics context can now correctly handle contexts residing on different threads.

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

String and image drawing is now thread-safe.

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

Using color and font objects in multiple threads is now safe to do.

David Duncan在他的评论中证实了这一点这里

David Duncan confirms this in his comments here.

除此之外,关于UIKit的其他一切都不被认为是线程安全的,所以你应该确保你在主线程上与它进行交互在这些情况下。

Beyond that, pretty much everything else regarding UIKit is not considered threadsafe, so you should make sure you are interacting with it on the main thread in those cases.

顺便说一句,我更喜欢我的基于块的在你链接的宏上执行总是在主线程上运行功能,因为我喜欢e xplicit包装需要在主线程上运行的代码。

As an aside, I do prefer my block-based implementation of a "always run on the main thread" function over the macro you link to, because I like the explicit wrapping of code that needs to be run on the main thread.

这篇关于什么需要在主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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