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.
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.
NSUInteger i = arc4random();
NSString *string = [tips objectAtIndex: i];
-(NSString *) returnArrayItem: (NSArray *) array {
//Sets randNum equal to a random number between 0 and the number of elements in the array parameter
NSUInteger randNum = arc4random() % [array count];
//Sets the string returnValue to a random string in the array
NSString *returnValue = [array objectAtIndex:randNum];
//Returns array
return returnValue;
}
Hope this helps