I have an NSArray which contains 10 objects from index 0 - 9. Each entry in the array is a quotation.
When my user selects the 'random quote' option I want to be able to select a random entry from the array and display the text that is contained in that entry.
Can anyone point me in the right direction on how to achieve this?
I'd recommend you use this instead of hardcoding the 10; that way, if you add more quotations, it will work it out automatically, without you needing to change that number.
NSInteger randomIndex = arc4random()%[array count];
NSString *quote = [array objectAtIndex:randomIndex];
Your probably going to want to use arc4random() to pick an object from 0-9. Then, simply do
NSString* string = [array objectAtIndex:randomPicked];
to get the text of the entry.
You can use arc4random()%10
to get an index. There is a slight bias that should not be a problem.
Better yet use arc4random_uniform(10)
, there is no bias and is even easier to use.
First, get a random number between your bounds, see this discussion and the relevant man pages. Then just index into the array with it.
int random_number = rand()%10; // Or whatever other method.
return [quote_array objectAtIndex:random_number];
Edit: for those who can't properly interpolate from the links or just don't care to read suggested references, let me spell this out for you:
// Somewhere it'll be included when necessary,
// probably the header for whatever uses it most.
#ifdef DEBUG
#define RAND(N) (rand()%N)
#else
#define RAND(N) (arc4random()%N)
#endif
...
// Somewhere it'll be called before RAND(),
// either appDidLaunch:... in your application delegate
// or the init method of whatever needs it.
#ifdef DEBUG
// Use the same seed for debugging
// or you can get errors you have a hard time reproducing.
srand(42);
#else
// Don't seed arc4random()
#endif
....
// Wherever you need this.
NSString *getRandomString(NSArray *array) {
#ifdef DEBUG
// I highly suggest this,
// but if you don't want to put it in you don't have to.
assert(array != nil);
#endif
int index = RAND([array count]);
return [array objectAtIndex:index];
}