自 Xcode 10 起,UIImageView setImage 在后台线程上崩溃
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52448204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UIImageView setImage crashes on background thread since Xcode 10
提问by Laurent Crivello
Since Xcode 10 on iOS, the following is crashing with:
[Animation] +[UIView setAnimationsEnabled:] being called from a background thread. Performing any operation from a background thread on UIView or a subclass is not supported and may result in unexpected and insidious behavior. trace=...
从 iOS 上的 Xcode 10 开始,以下内容崩溃了:
[Animation] +[UIView setAnimationsEnabled:] being called from a background thread. Performing any operation from a background thread on UIView or a subclass is not supported and may result in unexpected and insidious behavior. trace=...
when launched from background thread.
从后台线程启动时。
+(UIImage *)circularImage:(UIImage *)image withDiameter:(NSUInteger)diameter
{
CGRect frame = CGRectMake(0.0f, 0.0f, diameter, diameter);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
[imageView setImage:image]; <--- crashing here
...
}
Is that normal that I can't assign a simple UIImage to an UIImageView in a background thread ?
我不能在后台线程中将简单的 UIImage 分配给 UIImageView 是否正常?
回答by Jay Mayu
You can access the UI elements only from the main thread. You can't access it from other threads. That's why the app is crashing. Use the code below.
您只能从主线程访问 UI 元素。您无法从其他线程访问它。这就是应用程序崩溃的原因。使用下面的代码。
dispatch_async(dispatch_get_main_queue(), ^{
//update your UI stuff here.
});
You could do the same with Swift as below.
你可以用 Swift 做同样的事情,如下所示。
DispatchQueue.main.async { // your UI stuff here }
Thanks to @lenooh for pointing it out.
感谢@lenooh 指出。