Use this code:
uint32_t rnd = arc4random_uniform([tips count]); NSString *randomObject = [tips objectAtIndex:rnd];
EDIT: While working on my project, I decided to create a category for NSArray. It is very simple, but I found it useful.
Here are the files:
NSArray + Random.h
NSArray + Random.m
#import "NSArray+Random.h" @implementation NSArray (Random) -(id)randomObject { NSUInteger myCount = [self count]; if (myCount) return [self objectAtIndex:arc4random_uniform(myCount)]; else return nil; } @end
Then in the current example, you use it as follows:
NSString *randomObject = [tips randomObject];
Using a category has another advantage: when you decide to change the way random objects are selected in your application, you simply change the randomObject method.
Adam May 31 '12 at 16:19 2012-05-31 16:19
source share