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

我应该做些什么改变?有谁能帮我解决

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

以下:

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

应改为:

NSInteger nElements = count;
NSInteger n = (arc4random() % nElements);
于 2012-12-21T09:31:46.423 回答
0
[words exchangeObjectAtIndex:i withObjectAtIndex:n];

在上面的语句中,两者in值都应该小于words计数(这里是 4)。否则,你会得到例外。

于 2012-12-21T09:14:18.503 回答