问题描述
for (int i = 0; i< [optionDataArr count]; i++) {
NSString *sName = [[optionDataArr objectAtIndex:i] objectForKey:kOptionName];
NSString *sPrice = [[optionDataArr objectAtIndex:i] objectForKey:kOptionExtraPrice];
if (sName.length == 0 && sPrice.length == 0) {
[optionDataArr removeObjectAtIndex:i];
}
}
假设 optionDataArr
包含一个没有值的字典,当上面的代码执行时,我收到:
Suppose optionDataArr
contains a dictionary having no values and when above code executes i receive:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
推荐答案
使用普通的旧 for 循环时可以删除项目,而使用快速枚举时则不能.
You can remove items when using a plain old for loop, you cannot when using fast enumeration.
不过,您的代码有问题.当您删除第 n 个元素时,下一个元素将是第 (n+2) 个.您需要手动将索引减 1 以说明移动的元素.
Your code is buggy, though. When you delete the nth element, the next element will be (n+2)th. You need to manually decrement the index by one to account for the shifted elements.
还请记住,在这种情况下,您确实需要对循环中的数组长度进行实时"边界检查,而不仅仅是使用保存长度的临时变量(或者您需要将其递减为嗯).
Also keep in mind, that in this case you really need to do "real time" bounds checking of the array length in the loop, and not just use a temporary variable holding the length (or you need to decrement that one as well).
这篇关于迭代时是否可以从 mutablearray 中删除字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!