UIImageView setImage crashes on background thread since Xcode 10

Viewed 7480

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

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 ?

1 Answers

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.

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

You could do the same with Swift as below.

DispatchQueue.main.async { // your UI stuff here }

Thanks to @lenooh for pointing it out.

Related