Alex Rivera | Logout

Get random object from Array

Asked 2011-09-28T08:28:19.237
14

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

Edit
Report

1 Answer

36
@interface NSArray (Random)
- (id) randomObject;
@end

@implementation NSArray (Random)

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

@end
answered 2011-09-28T08:34:15.117

Your Answer