Search code examples
objective-carrayscocoarandomnsarray

Pick random element of NSArray in Objective-C


Possible Duplicate:
Picking a Random Object in an NSArray

I have have an array in Objective-C with strings:

NSArray *tips;
tips = [NSArray arrayWithObjects:
       @"Foo",
       @"Bar",
       @"Baz",
       nil];

I want a method that takes a random item from the array, and returns it. Is there a method, or how can I write one myself? Thanks.


Solution

  • 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's very simple but i found it useful.

    Here are the files:

    NSArray+Random.h

    #import <Foundation/Foundation.h>
    
    @interface NSArray (Random)
    
    - (id)randomObject;
    
    @end
    

    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 like this:

    NSString *randomObject = [tips randomObject];
    

    Using category has another advantage: when you decide to change your way of selecting random objects in your app you just modify the randomObject method.