0

I am drawing a complex view in my background queue and then add it as a subview to my collection view's content view, but it takes forever to do so.

Here's my code:

[self.drawingOperationQue addOperationWithBlock:^{

    ObservationViewSmall *observationSmall = [[ObservationViewSmall alloc] initWithFrame:CGRectMake(0, 0, 408, 332)];
    [observationSmall initViewWithObservation:[self.childObservationArray objectAtIndex:indexPath.row]];
    cell.userInteractionEnabled = YES;

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [cell.contentView addSubview:observationSmall];

    }];

}];

Any help is more than welcome.

akashivskyy
  • 44,342
  • 16
  • 106
  • 116
Junaid Ahmed
  • 175
  • 1
  • 9
  • Pay attention that mostly of UIKit elements are not thread safe. It seems altho you are creating a UIView subclass in a background queue, I don't think you can do it. Of course you can draw on background thread using graphics context. – Andrea Jun 29 '15 at 12:27

1 Answers1

0

Referring to this answer: https://stackoverflow.com/a/11123184/190599

You are creating your view off the main thread.

The following would create your view on the main thread:

[self.drawingOperationQue addOperationWithBlock:^{

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        ObservationViewSmall *observationSmall = [[ObservationViewSmall alloc] initWithFrame:CGRectMake(0, 0, 408, 332)];
        [observationSmall initViewWithObservation:[self.childObservationArray objectAtIndex:indexPath.row]];
        cell.userInteractionEnabled = YES;
        [cell.contentView addSubview:observationSmall];
    }];

}];
Community
  • 1
  • 1
CodeReaper
  • 5,988
  • 3
  • 35
  • 56
  • isn't this the whole idea? create your view (draw them) in the backgorund then add them in the main thread? I also tried that but then it blocks the UI. The scrolling of the collection view becomes jittery – Junaid Ahmed Jun 29 '15 at 12:33
  • @JunaidAhmed The init of the view and adding it as a subview should happen on the main view, the extra work you are doing in the two init calls done on ObservationViewSmall you need to separate out and away from the main thread. – CodeReaper Jun 29 '15 at 13:30
  • @CodeReaper, why did you use addOperationWithBlock inside addOperationWithBlock ? this makes no sense in this context – Doro Jun 29 '15 at 14:10
  • @Doro Because I do not know what other operations Junaid puts in the drawingOperationQueue. Adding to the main queue inside of the drawingOperationQueue maintains the current behavior. On the other hand, if there is only added these blocks for init'ing ObservationViewSmalls, then you might as well use the main queue straight away. – CodeReaper Jun 29 '15 at 18:31
  • guys i override the drawRect function of my view to draw my custom drawing. Once that's been drawn, the idea was to add the drawn view into the cell's content view in the main thread. – Junaid Ahmed Jun 29 '15 at 23:20