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

标签 ios xcode uiimage background-process

这个问题在这里已经有了答案:





Can we update UI from background Thread?

(1 个回答)


3年前关闭。




从 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(), ^{
    //update your UI stuff here.
});

你可以用 Swift 做同样的事情,如下所示。
DispatchQueue.main.async { // your UI stuff here }

感谢@lenooh 指出。

关于ios - 自 Xcode 10 起,UIImageView setImage 在后台线程上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52448204/

相关文章:

ios - 如何让我的 CollectionView 单元格从我的 TableView 中过滤数据?

iOS UI 测试 : Handle all system prompt automatically with addUIInterruptionMonitorWithDescription

objective-c - 如何为 Storyboard中的每个 View 分配名称

ios - UI 图像/多 View Controller

ios - 如何在 iOS 中制作带边框的图像?

objective-c - 从 AppDelegate 更改选项卡和推送 View

ios - 如何检测用户点击了 UIMenuController 中的格式化按钮?

ios - 通过 IBInspectable 属性实时渲染 IBOutlet 连接的 subview

ios - 在 ViewController 中创建选项卡 View 的最佳方法是什么

arrays - Swift 中 UIImage 到 String 和 String 到 UIImage