Reputation: 251
Im using four buttons and shuffle the button tag value to view different values on each click, Since i show the value of button from array, While am trying to shuffle the tag value i got following error.
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray exchangeObjectAtIndex:withObjectAtIndex:]: index 16 beyond bounds [0 .. 3]'
My code for shuffling the array of tag value,
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];
}
What change should i made??Can any one help me to solve
Upvotes: 2
Views: 95
Reputation: 3905
You have to select an image from quester
first. You created the index n
to take object from quester
array no?
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];
}
Or if you want to exchange within the array change count
as :
NSUInteger count = [words count];
Upvotes: 1
Reputation: 19153
The following:
NSInteger nElements = count - i;
NSInteger n = (arc4random() % nElements) + i;
Should be changed to:
NSInteger nElements = count;
NSInteger n = (arc4random() % nElements);
Upvotes: 0
Reputation: 17478
[words exchangeObjectAtIndex:i withObjectAtIndex:n];
In the above statement, both i
and n
should have a value less than the words
count (here it is 4). Else, you would get exception.
Upvotes: 0