3

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 ?

Laurent Crivello
  • 3,809
  • 6
  • 45
  • 89
  • 1
    Don't update UI in a background thread always use **dispatch_async(dispatch_get_main_queue(), ^{});** – Shehata Gamal Sep 21 '18 at 17:06
  • 3
    Normal and crucial. Your code was always wrong; now you're busted. You might say: but this UIImageView is not in the interface! That doesn't matter. UIKit is _not thread-safe_. – matt Sep 21 '18 at 17:10

1 Answers1

14

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.

Jay Mayu
  • 17,023
  • 32
  • 114
  • 148