2

4 つのボタンを使用し、ボタン タグの値をシャッフルして、クリックごとに異なる値を表示します。配列からボタンの値を表示するため、タグの値をシャッフルしようとしているときに次のエラーが発生しました。

  *** 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];
}

どのような変更を加える必要がありますか??誰かが解決するのを手伝ってくれますか?

4

3 に答える 3

1

quester最初から画像を選択する必要があります。配列nからオブジェクトを取得するためのインデックスを作成しましたか?quester

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];
于 2012-12-21T09:26:58.137 に答える
0
[words exchangeObjectAtIndex:i withObjectAtIndex:n];

上記のステートメントでは、iとの両方の値がカウントnよりも小さい必要があります(ここでは4です)。wordsそうしないと、例外が発生します。

于 2012-12-21T09:14:18.503 に答える
0

以下:

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

次のように変更する必要があります。

NSInteger nElements = count;
NSInteger n = (arc4random() % nElements);
于 2012-12-21T09:31:46.423 に答える