因未捕获的异常'NSGenericException'而终止应用程序,原因:'*** Collection< __ NSArrayM:0x117540>在被列举时被突变

时间:2011-01-19 08:02:53

标签: iphone objective-c

当我的代码如下所示时,我开始了“收集是变异的,而beign枚举”异常:

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--;
            }

        }      

    }

任何人都可以告诉我代码中的错误以及如何解决问题。

感谢所有人, 马丹。

1 个答案:

答案 0 :(得分: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];