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

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

问题描述

我写了一个名为 ensureInMainThread 的小定义(我经常使用它).但是,我不确定在主线程上调用了哪些用户界面方法需要.setNeedsDisplaysetNeedsLayout 呢?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:

推荐答案

从 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.

顺便说一句,我更喜欢我的始终在主线程上运行"函数的基于块的实现在您链接到的宏上,因为我喜欢需要在主线程上运行的代码的显式包装.

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天全站免登陆