Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting exception as "Collection was mutated while being enumerated"

I am getting the Collection was mutated while being enumerated exception when I am using this code can any one suggest me how to get out of this.

PaymentTerms * currentElement;
for (currentElement in termsArray)
{
    printf("\n currentElement Value........%s",[currentElement.days UTF8String]);
    printf("\n Str value...%s",[Str UTF8String]);
    NSRange range = [currentElement.days rangeOfString:Str options:NSCaseInsensitiveSearch];
    if(!(range.location != NSNotFound))
    {
        PaymentTerms *pTerm1 = [[PaymentTerms alloc]init];
        pTerm1.days = Str;
        printf("\n  pTerm1.days...%s",[ pTerm1.days UTF8String]);
        [termsArray addObject:pTerm1];
    }   
}

Hope I get quick response from ur side. Thank in advance, Monish.

like image 819
Monish Kumar Avatar asked Aug 06 '10 14:08

Monish Kumar


2 Answers

You cannot change array while you're enumerating it. As a workaround you should accumulate new objects in temporary array and add them after enumeration:

PaymentTerms * currentElement;
NSMutableArray* tempArray = [NSMutableArray array];
for (currentElement in termsArray)
{
    NSRange range = [currentElement.days rangeOfString:Str options:NSCaseInsensitiveSearch];
    if(!(range.location != NSNotFound))
    {
       PaymentTerms *pTerm1 = [[PaymentTerms alloc]init];
       pTerm1.days = Str;
       [tempArray addObject:pTerm1];
       [pTerm1 release];
    }   
}
[termsArray addObjectsFromArray: tempArray];

P.S. do not forget to release pTerm1 object you create - your code contains memory leak

In respond to poster's comment (and actual task) - I think the easiest way to make bool flag indicating if day value was found in cycle. If not - add new object after cycle ends:

PaymentTerms * currentElement;
BOOL dayFound = NO;
for (currentElement in termsArray)
{
    NSRange range = [currentElement.days rangeOfString:Str options:NSCaseInsensitiveSearch];
    if(range.location != NSNotFound)
        dayFound = YES;
}
if (!dayFound)
     // Create and add new object here
like image 195
Vladimir Avatar answered Nov 03 '22 20:11

Vladimir


This line [termsArray addObject:pTerm1]; will throw that exception. You CANNOT add/delete an element from an array inside a for each loop. for (currentElement in termsArray)

like image 23
vodkhang Avatar answered Nov 03 '22 20:11

vodkhang