2012-12-21 70 views
2

林。拋去陣列捕獲的異常

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray exchangeObjectAtIndex:withObjectAtIndex:]: index 16 beyond bounds [0 .. 3]' 

我洗牌標籤值的陣列碼,

words = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3",@"4", nil] ; 

NSUInteger count = [questar count]; 
for (NSUInteger i = 0; i < count; ++i) { 
    // Select a random element between i and end of array to swap with. 
    NSInteger nElements = count - i; 
    NSInteger n = (arc4random() % nElements) + i; 
    [words exchangeObjectAtIndex:i withObjectAtIndex:n]; 
} 

,我應該做出什麼樣的變化?任何一個可以幫助我解決

+1

在哪裏'count'變量定義了嗎? – Eimantas

+0

@Eimantas對不起。現在問題更新 –

+1

什麼是questar? – Ilanchezhian

回答

0
[words exchangeObjectAtIndex:i withObjectAtIndex:n]; 

在上面的語句,既in應該有一個值比words數少(這裏是4)。否則,你會得到例外。

1

你必須首先從quester選擇圖像。你創建索引nquester數組中取對象沒有?

words = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3",@"4", nil] ; 

NSUInteger count = [questar count]; 
for (NSUInteger i = 0; i < count; ++i) 
{ 
    // Select a random element between i and end of array to swap with. 
    NSInteger nElements = count - i; 
    NSInteger n = (arc4random() % nElements) + i; 

    currentImage = [questar objectAtIndex:n]; 

    [words replaceObjectAtIndex:i withObject:currentImage]; 
} 

或者,如果你想爲陣列變化count內交換:

NSUInteger count = [words count]; 
0

以下:

NSInteger nElements = count - i; 
NSInteger n = (arc4random() % nElements) + i; 

應改爲:

NSInteger nElements = count; 
NSInteger n = (arc4random() % nElements);