我在更新 NSMutableDictionary 值时遇到了一个奇怪的问题。我正在运行一个 for-in 循环,所有内容都可以正常检索,而且我的数学也很好。
问题出在我尝试使用 setValue: forKey:
方法更新我的字典时。
for(NSString *key in self.planetDictionary){
if(![key isEqualToString:planet]){
* * *
//do some math and stuff, create an NSNumber:
NSNumber *update = [NSNumber numberWithFloat:updatedProbability];
//Problem code, EXC_BAD_ACCESS here:
[self.planetDictionary setValue:update forKey:key];
}
}
我遇到 EXC_BAD_ACCESS 崩溃。我可以确认其他一切都很好,它只是我尝试更新值的一行。
这是怎么回事?谢谢
最佳答案
您不能改变正在快速枚举的对象。每次都会崩溃。作为解决方法,您可以先制作一份副本:
NSDictionary *dictionary = [self.planetDictionary copy];
for (NSString *key in dictionary) {
if (![key isEqualToString:planet]) {
NSNumber *update = [NSNumber numberWithFloat:updatedProbability];
[self.planetDictionary setValue:update forKey:key];
}
}
或者,如果你的字典中有大对象(符合 NSCopying
,否则它只是一个浅拷贝并且不会很重要),因此你不需要想要复制所有对象,那么您可以简单地复制键(作为数组)并像这样枚举它们:
NSArray *keysCopy = [[self.planetDictionary allKeys] copy];
for (NSString *key in keysCopy) {
if (![key isEqualToString:planet]) {
NSNumber *update = [NSNumber numberWithFloat:updatedProbability];
[self.planetDictionary setValue:update forKey:key];
}
}
关于iphone - 无法从 for-in 循环中更新 NSMutableDictionary 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15889047/