Search code examples
objective-copencvuiimageviewuiimage

UIImageView setImage not working in a delegate method?


I have a problem calling the setImage function in the opencv delegate method processImage.
When I call setImage in viewDidLoad, I can see the image, but when I do the same in processImage, it doesn't work.

What's the problem here?

- (void)viewDidLoad
{
  [super viewDidLoad];

  // This works !
  [processImageView setImage:[UIImage imageNamed:@"resistor3.jpg"]];
}

- (void)processImage:(cv::Mat&)img   {

  // This does not work anymore !
  [processImageView setImage:[UIImage imageNamed:@"resistor3.jpg"]]; 
}

Solution

  • When you modify the UI you must do it from the main thread, chances are that the delegate method, if it's being called, is called on another thread. Try this.

    - (void)processImage:(cv::Mat&)img   {
        dispatch_async(dispatch_get_main_queue(), ^{
            [processImageView setImage:[UIImage imageNamed:@"resistor3.jpg"]];
            // I also think you should use the dot syntax, but that's purely a style thing
            // processImageView.image = [UIImage imageNamed:@"resistor3.jpg"];
        });
    }
    

    EDIT: Add recommendation about using dot syntax