自Xcode 10以来,UIImageView setImage在后台线程上崩溃[重复]

Posted

技术标签:

【中文标题】自Xcode 10以来,UIImageView setImage在后台线程上崩溃[重复]【英文标题】:UIImageView setImage crashes on background thread since Xcode 10 [duplicate] 【发布时间】:2018-09-21 17:01:01 【问题描述】:

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

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

【问题讨论】:

不要在后台线程中更新 UI 总是使用 dispatch_async(dispatch_get_main_queue(), ^); 正常而关键。你的代码总是错的;现在你破产了。你可能会说:但是这个 UIImageView 不在界面中!那没关系。 UIKit 不是线程安全的 【参考方案1】:

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

dispatch_async(dispatch_get_main_queue(), ^
    //update your UI stuff here.
);

你可以用 Swift 做同样的事情,如下所示。

DispatchQueue.main.async  // your UI stuff here 

感谢@lenooh 指出。

【讨论】:

对于 Swift,应该是:DispatchQueue.main.async // your UI stuff here

以上是关于自Xcode 10以来,UIImageView setImage在后台线程上崩溃[重复]的主要内容,如果未能解决你的问题,请参考以下文章

自 Xcode 11 以来 UITableViewCellReorderControl 默认颜色错误

自 xcode 6.3 以来的 NSLayoutconstraint 损坏

自 Xcode 6.3 以来可能出现的新 iBeacon 监控问题

XCode 6.1 UIImageView 消失

自 Xcode 5.1 以来无法在 cocoapods 中构建模块“UIKit”

自 Xcode 12 (Swift 5.3) 以来,嵌套集合视图不响应单元格选择