Objective-c – Getting exception as “Collection was mutated while being enumerated”

iphoneobjective c

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.

Best Answer

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