2012-10-06 94 views
0

我调用getHoleScore方法来填充NSMutableArray并返回它。我试图阵列复制,以便调用方法可以访问该项目,但每一次我得到这个异常:Objective-C:复制返回的NSMutableArray

异常“NSRangeException”,原因是:“* - [__ NSArrayM objectAtIndex:]:索引0超越空阵列'

我已经尝试了多种不同的方式来复制我在这个网站上找到的一个数组,但是没有任何东西可以工作。下面的代码:

Score *theScore = self.roundScore; 
NSMutableArray *scores = [[[self delegate]getHoleScore:self score:theScore] mutableCopy]; 
NSInteger total = 0; 

if (theScore) { 
    self.playerName.text = theScore.name; 
    self.courseName.text = theScore.course; 
    self.hole1Field.text = [NSString stringWithFormat:@"%d", [[scores objectAtIndex:0] integerValue]]; 
    self.hole2Field.text = [NSString stringWithFormat:@"%d", [[scores objectAtIndex:1] integerValue]]; 
    self.hole3Field.text = [NSString stringWithFormat:@"%d", [[scores objectAtIndex:2] integerValue]]; 
    self.hole4Field.text = [NSString stringWithFormat:@"%d", [[scores objectAtIndex:3] integerValue]]; 
    self.hole5Field.text = [NSString stringWithFormat:@"%d", [[scores objectAtIndex:4] integerValue]]; 

如何填充分数阵列的任何想法?

+0

如果你调用NSLog(@“%@”,得分),那么''NSMutableArray * scores'声明之后呢? –

+0

我只是得到一个开放的括号,然后是相同的异常。 – user1040854

+0

在哪一行你会得到这个异常?你能告诉我们getHoleScore的定义吗? – nagan

回答

1

对于您的可变数组,您已经达到0,因为它尚未被alloc/init。你必须把这个NSMutableArray *myscores = [NSMutableArray array];放在你[[self delegate]]之上。

或者一个更好的方法来做到这一点将创建你的myscores和传递方法在这个内置的nsarray超类方法,该方法负责alloc/init你的数组。

NSMutableArray *myscores = [NSMutableArray arrayWithArray:[[self delegate] getHoleScore:self score:theScore];

也确保 [[self delegate]getHoleScore:self score:theScore]不向您发送空数组,调用-objectAtIndex:一个一个空数组会崩溃你的代码。检查数组是否为空的好方法是调用数组的方法-count方法,调用数组的方法不会导致代码崩溃,即使它为零。

+1

hm,no。该数组可以正确地分配/插入(通过'-mutableCopy')。只是数组可能是空的(没有元素),因此访问'objectAtIndex:0'不在数组的边界内。 – Julien

0

嘿谢谢大家的帮助。你是对的,getHoleScore返回零。它正在关闭一个sqlite数据库,但一旦我清除它,然后重新添加数据,一切正常。

相关问题