Get random object from Array

Sonu picture Sonu · Sep 28, 2011 · Viewed 15.8k times · Source

I want to get random object from array, is there any way how can I find random object from mutable array?

Answer

zoul picture zoul · Sep 28, 2011
@interface NSArray (Random)
- (id) randomObject;
@end

@implementation NSArray (Random)

- (id) randomObject
{
     if ([self count] == 0) {
         return nil;
     }
     return [self objectAtIndex: arc4random() % [self count]];
}

@end