2011-01-19 23 views
2

當我的代碼如下所示時,我開始了「Collection was mutates while beenumerated」 :由於未捕獲的異常'NSGenericException'而終止應用程序,原因:'*** Collection <__ NSArrayM:0x117540>在枚舉時發生了變化

NSString *poiStr = nil; 
    int SuccessValue=0; 
    NSMutableArray* poisArray=[[NSMutableArray alloc]init]; 
    for (id<MKAnnotation> annotation in mainMapView.annotations) 
    { 
     MKAnnotationView* anView = [mainMapView viewForAnnotation: annotation]; 
     if(anView) 
     { 

      POI* locationPOI = (POI*)[anView annotation]; 
      printf("\n Location poi shape groupId:%s=====%s",[locationPOI.shapeSpaceGroupId UTF8String],[poiStr UTF8String]); 
      if((poiStr == nil) || ([poiStr isEqualToString:locationPOI.shapeSpaceGroupId])) 
      { 

       poiStr = locationPOI.shapeSpaceGroupId; 
       [poisArray addObject:locationPOI]; 
       SuccessValue++; 
      } 
      printf("\n successValue:%d",SuccessValue); 
      if(SuccessValue==2) 
      { 
       POI* poi=[poisArray objectAtIndex:0]; 
       [mainMapView removeAnnotation:poi]; 
       SuccessValue--; 
      } 

     }  

    } 

任何人都可以請建議我什麼是錯誤的代碼和如何解決問題。

感謝所有, 馬丹。

+2

你而迭代modyfing。你不能做那樣的事情。註釋掉[mainMapView removeAnnotation:poi];並查看是否仍有異常 – 2011-01-19 08:06:10

+2

@Kamil請將其作爲回答發佈。 – 2011-01-19 08:11:56

回答

11

基本上你正在修改循環中的列表,你正在迭代它。導致問題的線是:

[mainMapView removeAnnotation:poi]; 

當您在mainMapView.annotations上進行迭代時。一種可能的解決方案是將您想要刪除的元素累積到不同的列表中,並在循環之後將其刪除。

基於您的代碼,一個可能的解決辦法是:

 NSString *poiStr = nil; 
    int SuccessValue=0; 
    NSMutableArray* poisArray=[[NSMutableArray alloc]init]; 
    NSMutableArray *to_delete = [[NSMutableArray alloc] init]; 
    for (id<MKAnnotation> annotation in mainMapView.annotations) 
    { 
     MKAnnotationView* anView = [mainMapView viewForAnnotation: annotation]; 
     if(anView) 
     { 

      POI* locationPOI = (POI*)[anView annotation]; 
      printf("\n Location poi shape groupId:%s=====%s",[locationPOI.shapeSpaceGroupId UTF8String],[poiStr UTF8String]); 
      if((poiStr == nil) || ([poiStr isEqualToString:locationPOI.shapeSpaceGroupId])) 
      { 

       poiStr = locationPOI.shapeSpaceGroupId; 
       [poisArray addObject:locationPOI]; 
       SuccessValue++; 
      } 
      printf("\n successValue:%d",SuccessValue); 
      if(SuccessValue==2) 
      { 
       POI* poi=[poisArray objectAtIndex:0]; 
       //[mainMapView removeAnnotation:poi]; 
       [to_delete addObject:poi]; 
       SuccessValue--; 
      } 

     }  

    } 
    for (id<MKAnnotation> annotation in to_delete) 
      [mainMapView removeAnnotation:poi]; 

    [to_delete release]; 
相關問題