我使用四个按钮并随机按下按钮标签值以查看每次点击的不同值,因为我从数组中显示按钮的值,当我试图改变标签值时,我得到了跟随错误。
*** 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];
}
我应该做出什么改变?任何人都可以帮我解决
答案 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];
在上面的陈述中,i
和n
都应该具有小于words
计数的值(此处为4)。否则,你会得到例外。
答案 2 :(得分:0)
以下内容:
NSInteger nElements = count - i;
NSInteger n = (arc4random() % nElements) + i;
应改为:
NSInteger nElements = count;
NSInteger n = (arc4random() % nElements);