可以在后台线程上安全地使用NSLayoutManager吗?

时间:2014-05-01 02:50:11

标签: ios textkit nslayoutmanager

即使iOS文档说:

  

可以访问NLayoutManager,NSTextStorage和NSTextContainer   来自subthreads,只要应用程序保证从单个访问   线程。

我偶尔遇到这个例外:

  

由于未捕获的异常而终止应用   'NSInternalInconsistencyException',原因:'只在main上运行   线程!

这是回溯:

Exception Type:  SIGABRT
Exception Codes: #0 at 0x197bca58c
Crashed Thread:  7

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Only run on the main thread!'

Last Exception Backtrace:
0   CoreFoundation                       0x000000018afd2f50 __exceptionPreprocess + 132
1   libobjc.A.dylib                      0x00000001974dc1fc objc_exception_throw + 56
2   CoreFoundation                       0x000000018afd2e10 +[NSException raise:format:arguments:] + 112
3   Foundation                           0x000000018bb0ae20 -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 84
4   UIFoundation                         0x00000001940f0654 -[NSLayoutManager(NSPrivate) _resizeTextViewForTextContainer:] + 412
5   UIFoundation                         0x00000001940f0318 -[NSLayoutManager(NSPrivate) _recalculateUsageForTextContainerAtIndex:] + 1748
6   UIFoundation                         0x000000019411ec2c _enableTextViewResizing + 236
7   UIFoundation                         0x0000000194123e18 -[NSLayoutManager textContainerForGlyphAtIndex:effectiveRange:] + 484
8   UIFoundation                         0x0000000194125c60 -[NSLayoutManager glyphRangeForTextContainer:] + 352

有一点需要注意的是,我NLayoutManager附加了UITextView。您可以将其视为用于在后台线程中进行文本布局的普通UITextView

这是否意味着与文档所说的相矛盾,NLayoutManager如果附加到UITextView,则无法安全地在单个后台线程上使用?

1 个答案:

答案 0 :(得分:0)

在我看来,文档中的注释实际上解释了这个问题。由于您使用的是附加到UITextView的布局管理器,因此无法保证从单个线程访问它。最好假设文本视图可以随时访问布局管理器,特别是如果视图在屏幕上。你无法确切地知道它是如何使用布局管理器的,但可以肯定的是它发生在主线程上。

您可以让后台线程创建单独的NSLayoutManagerNSTextStorageNSTextContainer,进行所有布局计算,然后在主线程上应用这些计算。

相关问题