2012-10-06 68 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數據庫,但一旦我清除它,然後重新添加數據,一切正常。

相關問題