Search code examples
iphonearc4random

Get random object from Array


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


Solution

  • @interface NSArray (Random)
    - (id) randomObject;
    @end
    
    @implementation NSArray (Random)
    
    - (id) randomObject
    {
         if ([self count] == 0) {
             return nil;
         }
         return [self objectAtIndex: arc4random() % [self count]];
    }
    
    @end