2010-05-21 80 views
0

我试图在此函数调用 时将随机数添加到此数组的末尾。到目前为止,我已经缩小了它的范围。 当我检查,看看是否有任何数组,它说0. 所以现在我很难住。我在考虑MutableArray在我使用它们之前发布它的内容。问题是我不知道该用什么。一个按钮调用函数,几乎所有其他的东西都被处理掉了。向数组添加整数

NSMutableArray * choices; 

-(void) doSomething { 

int r = arc4random() % 4; 
//The problem... 
[choices addObject:[NSNumber numberWithInt:r]]; 

int anInt = [[choices objectAtIndex:1] integerValue]; 
NSLog(@"%d", anInt); 
    //I'm getting nothing no matter what I do. 

//some type of loop that goes through the array and displays each element 
//after it gets added 

} 
+0

我环顾四周,我没有看到它如何不诚实地工作。 – Ohmnastrum 2010-05-21 20:49:43

回答

2

当时选择过初始化?

... somewhere:choices = [[NSMutableArray alloc] init];

...然后,数组索引从0开始,所以[[colorChoices objectAtIndex:1]在第一次调用doSomething函数时不起作用。

+0

从未做过初始化。感谢提醒^^; 至于从1开始,我认为它没有问题,因为我按了2次以上。 – Ohmnastrum 2010-05-21 20:56:04

0

需要初始化choices

NSMutableArray* choices; 
choices = [[NSMutableArray alloc] init]; 
+0

我试图像这样初始化它(在它声明的同一个文件中)并且出现了几个错误。 – Ohmnastrum 2010-05-21 21:08:34

+0

好吧我在ibAction里面试过它,它工作。但是如果我想让阵列坚持整场比赛呢?它不会超出范围吗? – Ohmnastrum 2010-05-21 21:10:18

+0

让它成为你班级的一个属性,例如视图控制器或应用程序委托。然后,您可以在单一方法之外使用它。 – 2010-05-21 21:54:01