重要的是使用`performSelectorOnMainThread:withObject:waitUntilDone:`从NSOperation? [英] How Important is it to use `performSelectorOnMainThread:withObject:waitUntilDone:` From an NSOperation?

查看:119
本文介绍了重要的是使用`performSelectorOnMainThread:withObject:waitUntilDone:`从NSOperation?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的iPad应用程式与XML资讯提供同步,在NSOperationQueue执行的NSOperation子类别中执行同步作业。当它解析feed时,它通过 performSelectorOnMainThread:withObject:waitUntilDone:回调到主线程,以更新UI的各个部分,计划下载等。相当贵由于同步正在进行,UI有时可能无法响应一秒或两秒。

My iPad app syncs with an XML feed, running the sync in an NSOperation subclass executed from an NSOperationQueue. As it parses the feed, it calls back to the main thread via performSelectorOnMainThread:withObject:waitUntilDone: to update various parts of the UI, schedule downloads, etc. Some of this is pretty expensive; the UI can sometimes become unresponsive for a second or two as a sync is going on.

为了使用户界面更具响应性,我删除了使用 performSelectorOnMainThread:withObject:waitUntilDone:有利于直接调用执行所有与同步相关的任务,包括更新UI。所以现在同步完全发生在由NSOperationQueue创建的后台线程上。这似乎工作得很好,并且UI在同步期间响应更快。

To make the UI more responsive, I've removed the use of performSelectorOnMainThread:withObject:waitUntilDone: in favor of direct calls to perform all the sync-related tasks, including updating the UI. So now the sync takes place entirely on the background thread created by the NSOperationQueue. This seems to work pretty well, and the UI is much more responsive during a sync.

但是,我很愿意这样发布。我在各个地方看到一些提到,只应该更新主线程上的UI(关于AppKit的示例)。但我在文档中找不到任何特定于此主题的内容。

However, I'm leery of releasing with it this way. I've seen some mentions in various places that one should only update the UI on the main thread (example with reference to AppKit). But I've been unable to find anything specific on this topic in the documentation.

因此,在主线程上更新UI有多重要?应用程序的哪些部分是线程安全的,哪些不是?是否有可能参考解释什么是安全的执行在NSOperation和什么应该只执行在iOS的主线程?

So how important is it to update the UI on the main thread? Which parts of an app are thread-safe and which are not? Is there perhaps a reference explaining what's safe to execute in an NSOperation and what should be executed only on the main thread in iOS? Am I really doing something unsafe or crash-prone?

推荐答案

这是非常重要的,你总是更新主线程的UI 。从后台线程触摸UI可能会导致各种问题,包括内部状态的损坏,崩溃或仅仅是不正确的行为。任何不需要触摸UI的工作都应该在后台线程上进行,但是更新UI的代码段肯定需要在主线程上发生。

It is extremely important that you always update the UI on the main thread. Touching the UI from a background thread can cause all sorts of issues, including corruption of internal state, crashes, or just plain incorrect behavior. Any work that doesn't require touching the UI should go ahead and do on the background thread, but the bits of code that update the UI definitely needs to happen on the main thread.

这篇关于重要的是使用`performSelectorOnMainThread:withObject:waitUntilDone:`从NSOperation?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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