自Xcode 10起,UIImageView setImage在后台线程上崩溃

Lau*_*llo 2 xcode background-process uiimage ios

从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=...

从后台线程启动时。

+(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
...
}
Run Code Online (Sandbox Code Playgroud)

我不能在后台线程中将简单的UIImage分配给UIImageView是正常的吗?

Jay*_*ayu 9

您只能从主线程访问UI元素。您不能从其他线程访问它。这就是应用程序崩溃的原因。使用下面的代码。

dispatch_async(dispatch_get_main_queue(), ^{
    //update your UI stuff here.
});
Run Code Online (Sandbox Code Playgroud)

您可以使用Swift进行以下操作。

DispatchQueue.main.async { // your UI stuff here }
Run Code Online (Sandbox Code Playgroud)

感谢@lenooh指出来。

  • 对于Swift,将是:`DispatchQueue.main.async {//您的UI此处}` (3认同)