CALayerArray 在枚举时发生了变异 [英] CALayerArray was mutated while being enumerated
问题描述
我必须时不时地删除数组的一个对象,当我这样做时,我得到这个错误.
I have to delete an object of an array every now and then, when I do it I get this error.
集合
Collection < CALayerArray: 0xc4f3b20> was mutated while being enumerated
错误出现在这个方法上,它是Array的访问者:
The error appears on this method, which is the accesor of the Array:
- (NSArray *)occupantsArray
{
if (dispatch_get_current_queue() == moduleQueue)
{
return occupantsArray;
}
else
{
__block NSArray *result;
dispatch_sync(moduleQueue, ^{ //ON THIS LINE
result = [occupantsArray copy];
});
return [result autorelease];
}
}
正如你所看到的,我不返回原始数组而是返回一个副本,但它仍然崩溃.
As you can see Im taking care of not returning the original array but a copy, but it still crashes.
还有我删除数组元素的方法是这个.
Also the method where Im deleting elements of the array is this.
- (void)eraseJIDFromArray:(NSString*)jid{
dispatch_block_t block = ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i = 0;
for(NSString *jidAct in occupantsArray){
if([jidAct isEqualToString:jid]){
[occupantsArray removeObjectAtIndex:i];
}
i++;
}
[pool drain];
};
if (dispatch_get_current_queue() == moduleQueue)
block();
else
dispatch_async(moduleQueue, block);
}
数组最多可以有 200 个元素,因此遍历所有元素可能需要一些时间,但我正在设置队列,不知道还能做什么.
The array can have upto 200 elements, so it can take some time to go through all of them, but I'm setting queues, dont know what else I can do.
有什么想法吗?
谢谢.
推荐答案
这段代码:
for(NSString *jidAct in occupantsArray){
if([jidAct isEqualToString:jid]){
[occupantsArray removeObjectAtIndex:i];
}
i++;
}
可能会导致您的问题.枚举数组时不应删除元素.避免这种情况的方法是使用 NSMutableIndexSet:
is probably causing your problems. You shouldn't be removing elements while enumerating the array. The way you avoid this is by using an NSMutableIndexSet:
NSMutableIndexSet *indexes = [NSMutableIndexSet set]; // assuming NSInteger i;
for(NSString *jidAct in occupantsArray){
if([jidAct isEqualToString:jid]){
[indexes addIndex:i];
}
i++;
}
[occupantsArray removeObjectsAtIndexes:indexes];
这篇关于CALayerArray 在枚举时发生了变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!