gpt4 book ai didi

objective-c - Collection was mutated while being enumerated 错误在 Objective-C

转载 作者:太空狗 更新时间:2023-10-30 03:39:07 27 4
gpt4 key购买 nike

下面是我的代码。

NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:@"5"];
[arr addObject:@"7"];
[arr addObject:@"8"];
[arr enumerateObjectsUsingBlock:^(NSString *obj,NSUInteger idx,BOOL *stop) {
[arr replaceObjectAtIndex:idx withObject:@"10"];
}];

我得到的异常日志

 *** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x742a580> was mutated while being enumerated.'
*** First throw call stack:
(0x1596012 0x12a3e7e 0x161ecc5 0x158fe1b 0x158fa16 0x158f925 0x2ba4 0x1e87b7 0x1e8da7 0x1e9fab 0x1fb315 0x1fc24b 0x1edcf8 0x25f8df9 0x25f8ad0 0x150bbf5 0x150b962 0x153cbb6 0x153bf44 0x153be1b 0x1e97da 0x1eb65c 0x29fd 0x2925)
libc++abi.dylib: terminate called throwing an exception

当我使用 for 循环时代码运行良好

for (int i = 0 ; i<  arr.count; i++) {
[arr replaceObjectAtIndex:i withObject:@"8"];
}

因此,当我使用 enumerateObjectsUsingBlock 时,我遇到了异常。但两者都是枚举。正确的 ?那为什么上层代码给出was mutated while being enumerated异常呢?

最佳答案

因为你的逻辑有问题。不允许在枚举期间改变集合。在后一种情况下,NSMutableArray 不知道您正在尝试枚举它,仅在第一种情况下。然后它提示,因为这是一个语义错误。您通常应该通过可变复制数组并改变副本,然后用更新后的副本替换原始数组来解决这类问题。

关于objective-c - Collection was mutated while being enumerated 错误在 Objective-C ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14457369/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com