洗牌数组未捕获异常

时间:2012-12-21 09:01:06

标签: iphone ios6 nsmutablearray

我使用四个按钮并随机按下按钮标签值以查看每次点击的不同值,因为我从数组中显示按钮的值,当我试图改变标签值时,我得到了跟随错误。

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

我应该做出什么改变?任何人都可以帮我解决

3 个答案:

答案 0 :(得分: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];

答案 1 :(得分:0)

[words exchangeObjectAtIndex:i withObjectAtIndex:n];

在上面的陈述中,in都应该具有小于words计数的值(此处为4)。否则,你会得到例外。

答案 2 :(得分:0)

以下内容:

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

应改为:

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