获取异常为“收集在枚举时发生变异”
当我使用此代码时,我正在使用枚举异常进行变异,任何人都可以建议我如何摆脱这个。
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];
}
}
希望我能得到你们的快速反应。
提前感谢,
Monish。
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。不要忘记发布你创建的pTerm1对象 - 你的代码包含内存泄漏
P.S. do not forget to release pTerm1 object you create - your code contains memory leak
响应海报的评论(和实际任务) - 我认为制作bool标志的最简单方法指示是否在周期中找到日值。如果不是 - 在周期结束后添加新对象:
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