Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection <CALayerArray: 0x1ed8faa0> was mutated while being enumerated

My app crashes some time while removing wait view from screen. Please guide me how can i improve code given below.


The wait view is only called when app is downloading something from server. and when it completed download then i call removeWaitView method.

Exception Type: NSGenericException

Reason: Collection was mutated while being enumerated.

+(void) removeWaitView:(UIView *) view{
    NSLog(@"Shared->removeWaitView:");
    UIView *temp=nil;
    temp=[view viewWithTag:kWaitViewTag];
    if (temp!=nil) {
        [temp removeFromSuperview];
    }
}

my waitview adding code is

 +(void) showWaitViewInView:(UIView *)view withText:(NSString *)text{
   NSLog(@"Shared->showWaitViewWithtag");
   UIView *temp=nil;
   temp=[view viewWithTag:kWaitViewTag];
   if (temp!=nil)
   {
       return;
   }
   //width 110 height 40
   WaitViewByIqbal *waitView=[[WaitViewByIqbal alloc] initWithFrame:CGRectMake(0,0,90,35)];
   waitView.center=CGPointMake(view.frame.size.width/2,(view.frame.size. height/2) -15); 
   waitView.tag=kWaitViewTag;    // waitView.waitLabel.text=text;
   [view addSubview:waitView];
   [waitView release]; 
}
like image 681
Iqbal Khan Avatar asked Feb 13 '13 13:02

Iqbal Khan


1 Answers

The exception is pretty clear - a collection (in this case something like an array) is being modified while it is also being enumerated.

In this specific case we are talking about array of layers, or better said, instances of UIView which are all backed up by layers.

The modifications happen when you are calling removeFromSuperview or addSubview. The enumeration can happen anytime during redrawing.

My guess is - you are not calling your methods from the main thread and the main thread is currently redrawing, so you'll get a racing condition.

Solution: call these methods only from the main thread.

like image 80
Sulthan Avatar answered Sep 25 '22 21:09

Sulthan