在后台线程上构建 UIViews [英] Building up UIViews on background thread
问题描述
我知道 UI 应该只在主线程上更新,但是是否可以在单独的线程上创建和添加子视图,只要它们不添加到可见视图中?它会导致内存和性能问题吗?这是一些示例代码.
I'm aware that the UI should only be updated on the main thread, but is it possible to create and add subviews on a separate thread, as long as they are not added to the visible view? Will it cause memory and performance issues? Here's some example code.
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
// do some fancy calculations, building views
UIView *aView = ..
for (int i, i<1000, i++)
{
UIView *subView = …
[aView addSubview:subView];
}
// Update UI on Main Thread
[queue addOperationWithBlock:^{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Update the interface
[self.view addSubview:aView];
}];
}];
}];
推荐答案
我对您为什么不想这样做的理解是 CALayer
由不是线程安全的内存支持.因此,您可以在后台线程上绘图,但不能渲染图层或操作视图.
My understanding of why you don't want to do this is that CALayer
is backed byy memory that isn't thread safe. So you can draw on a background thread, but not render layers or manipulate views.
因此,您要做的是将复杂的视图逻辑绘制到图像上下文中,并将图像传递给主线程以在图像视图中显示.
So what you do is draw your complex view logic into an image context and pass the image off to the main thread to be displayed in an image view.
希望这会有所帮助!
这篇关于在后台线程上构建 UIViews的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!