gpt4 book ai didi

objective-c - NSMutable 数组 - objectAtIndex : index beyond bounds

转载 作者:行者123 更新时间:2023-12-03 16:22:59 25 4
gpt4 key购买 nike

我正在尝试查看加载了 NSMutableArray 的 NSMutableDictionary,但我把它弄乱了,而且我不知道怎么办。我正在尝试加载更大的游戏问题列表,如果级别不正确则将其删除。在尝试删除之前我不会收到错误消息。任何人都可以看到这段代码中的缺陷吗?我将非常感激!

谢谢

~G

{
NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
NSString *GameLevel = [[NSString alloc] initWithFormat: [settings objectForKey:kLevelKey]];

NSBundle *Bundle = [NSBundle mainBundle];
NSString *PListPath = [Bundle pathForResource:@"questions" ofType:@"plist"];

NSMutableDictionary *Dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:PListPath];

self.QuestionDetailsByLevel = Dictionary;
[Dictionary release];

NSMutableArray *Components = [[NSMutableArray alloc] initWithArray:[QuestionDetailsByLevel allKeys]];
self.QuestionsByLevel = Components;

int QuestionCount = [self.QuestionsByLevel count] - 1;

for (int j = 0; j < QuestionCount - 1; j++)
{

NSString *SelectedQuestion = [self.QuestionsByLevel objectAtIndex:j];
NSMutableArray *Array = [QuestionDetailsByLevel objectForKey:SelectedQuestion];
self.QDetailsByLevel = Array;

NSString *level = [[NSString alloc] initWithFormat:[self.QDetailsByLevel objectAtIndex:Level]];

if (level != GameLevel)
[QuestionsByLevel removeObjectAtIndex:j];
}
}

最佳答案

除了其他人提到的其他问题外,让我们重点讨论为什么会出现越界错误。

这是相关的代码。

for (int j = 0; j < QuestionCount - 1; j++)
{

NSString *SelectedQuestion = [self.QuestionsByLevel objectAtIndex:j];
// ... snip ...
if (level != GameLevel) //Always happening in your current code
[QuestionsByLevel removeObjectAtIndex:j];
}

让我们看看这段代码经过几次迭代后会发生什么。

第一次迭代:

j == 0
self.QuestionsByLevel == [Q1, Q2, Q3, Q4, Q5]

SelectedQuestion = QuestionsByLevel[0] // Q1

// The following happens because you call removeObjectAtIndex:0
QuestionsByLevel = [Q2, Q3, Q4, Q5]

第二次迭代:

j == 1
self.QuestionsByLevel == [Q2, Q3, Q4, Q5]
SelectedQuestion = QuestionsByLevel[1] // Q3

// The following happens because you call removeObjectAtIndex:1
QuestionsByLevel = [Q2, Q4, Q5]

第三次迭代:

j == 2
self.QuestionsByLevel == [Q2, Q4, Q5]
SelectedQuestion = QuestionsByLevel[2] // Q5

// The following happens because you call removeObjectAtIndex:2
QuestionsByLevel = [Q2, Q4]

第四次迭代:

j == 3
self.QuestionsByLevel == [Q2, Q4]
SelectedQuestion = QuestionsByLevel[3] // CRASH!!!!

你能看出问题所在吗?您的 for 循环假设您将通过索引访问对象,但每次迭代之后,您都会从数组中删除一些内容,这会移动该点之后的所有索引。您不应该调用 removeObjectAtIndex:,因为您试图同时遍历该数组。

如果您只是想跳过特定对象,则可以在到达该对象时调用“继续”。如果您确实想将其从数组中删除,只需调用 [QuestionsByLevel removeObject:GameLevel] 即可。或者任何对您的情况有意义的事情。但请在遍历数组之前执行此操作。

关于objective-c - NSMutable 数组 - objectAtIndex : index beyond bounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1659423/

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