Detect UI actions outside of main thread

放肆的年华 提交于 2020-06-09 08:25:06

问题


Note: This question is related to Warn on calls to UIKit from background threads but does not give an answer on two of the approaches below.

I have a problem where the app screen blinks rapidly. I already had that problem in the past and it is due to updating the UI elements outside the main thread.

Therefore I've put the following code in many places:

assertMainThread();

which is:

#define assertMainThread() NSAssert([NSThread isMainThread],@"Method called using a thread other than main!")

Of course I cannot cover the whole code with assertMainThread() as there are many places and some code is used in a legitimate way by background GCD queues.

I looked at many places, but could not find a way for XCode or LLDB to tell me when a UI element is updated outside the main thread. I thought that one could use symbolic breakpoints or some other mechanism to break at the place where a common method in UIKit is called outside of main thread for example, but could not find a way.

I also thought that UIKit could warn at runtime when such a call is made? Or at least give us some tools to see help debug such problems.

Another approach I looked (but did not try) is to use some code coverage techniques and try to extract what thread was running at what point in the code visually, but did not go that route.

Do you have any idea on how to tackle the problem?


回答1:


Xcode 9 and later

Xcode 9 introduces a Main thread checker which sniffs for many relevant issues potentially performed out-of-main thread. You can enable this analyser the usual way in your Scheme options along with other runtime analysers.

Xcode 8.3 and earlier

Alternative, Xcode-way solution based on steipete's gist – symbolic breakpoint:

You can easily add breakpoints for some other methods on any UIKit class, like -[UIView setNeedsDisplay] etc.




回答2:


Starting with Xcode 9 Apple integrated an Main Thread Checker in Xcode which is enabled by default if you run you app in with the Xcode debugger.

It can be disabled/enabled in the scheme configuration under the diagnostics tab.




回答3:


Xcode 11/Swift version of @Michi 's answer



来源:https://stackoverflow.com/questions/16053475/detect-ui-actions-outside-of-main-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!