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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With