使用ObjectAtIndex可以提供超出边界的错误

Max*_*Max 0 iphone sdk objective-c nsmutablearray

我想做一些非常简单的事情,但是我得到了一个错误,我错过了什么?

int i;
int count;

TutorialAppDelegate *appDelegate = (TutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
Animals *aAnimal = (Animals *)[appDelegate.animals objectAtIndex:i];
count = [animals count];


if (i < count)
{
    NSLog(@"%@",aAnimal.animalName);
}
Run Code Online (Sandbox Code Playgroud)

错误:

 '*** -[NSMutableArray objectAtIndex:]: index 22510243 beyond bounds [0 .. 5]'
Run Code Online (Sandbox Code Playgroud)

0 ... 5是正确的!数组中只有6个值.

并使用

NSLog(@"%@",aAnimal.animalName);
Run Code Online (Sandbox Code Playgroud)

out函数返回正确的值,当我也将i更改为0时.

Obl*_*ely 5

你需要初始化我.

int i = 0;
Run Code Online (Sandbox Code Playgroud)

默认情况下,int不会设置为零或任何合理的值.您可以通过添加以下行来检查:

NSLog(@"Value of i without initialising is: %d", i);
Run Code Online (Sandbox Code Playgroud)