我什么时候需要担心 iOS 应用程序中的线程安全?
在编写通常的视图控制器代码时,我可以假设这只会从单个事件循环线程调用吗?我需要什么样的类才能保证线程安全?涉及多线程的常见情况有哪些?
When writing the usual view controller code, can I assume that this will only be called from a single event-loop thread? What kind of classes do I need to make thread-safe? What are the usual situations where multiple threads are involved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
并发编程指南可以是有帮助。
The Concurrency Programming Guide can be helpful.
并发编程指南很好。以下是一些需要记住的非常重要的事情。
– 您应该只从主线程更新 UI。这可以让你以微妙的方式...
– NSNotifications 将在触发它们的线程中接收。因此,如果您启动一个线程并订阅 NSNotification 以触发 UI 操作,那么您应该在收到它时检查您所在的线程。如果它不在主线程上,请使用 NSObject 的 PerformSelectorOnMainThread: withObject:waitUntilDone: 将其放在主线程上。
– 如果您正在非用户界面上下文中进行一些绘图,我相信核心图形现在是线程安全的。 (我相信 CATiledLayer 因此做了一些聪明的事情)
– 一般来说,对于视图控制器,您应该考虑的唯一事件循环是主线程上的事件循环。在另一个线程上创建自己的事件循环之前请三思。
The concurrency programming guide is good. Here are some super important things to keep in mind.
– You should only update UI from the main thread. This can get you in subtle ways...
– NSNotifications will be received in the thread from which they are fired. So if you launch a thread and subscribe to a NSNotification to trigger a UI action, you should check what thread you're on when you get it. If it's not on the main thread use NSObject's performSelectorOnMainThread: withObject:waitUntilDone: to get it on the main thread.
– If you're doing some drawing into a non-ui context, I believe core graphics is now thread safe. (I believe CATiledLayer does some clever things because of this)
– Generally for view controllers, the only event loop you should think about is the one on the main thread. Think twice before making your own event loop on another thread.
如果您正在编写普通的 UIViewController 代码,则无需担心 iOS 中的线程安全性。在 iOS 中,任何有关 UI 的消息都应该在主线程上运行。
如果您自己不在后台执行某些消息,通常情况下,您不必担心线程,在大多数情况下,它将始终在主线程上。
PS 像 Game Kit 这样的一些框架有时会在后台执行消息,但这与 UI 无关,Apple 的文档会警告您确保消息是否在主线程上运行。
If you are writing normal UIViewController code, you don't need to worry about thread-safety in iOS. In iOS, any message about UI should be running on the main thread.
If you don't perform some message in background by you self, normally, you don't have to worry about thread, in most situations, it will always be on the main thread.
P.S. Some Frameworks like Game Kit will some times perform messages in background, but it's not about UI and the document from Apple will warn you to make sure if the message is running on main thread.