Select a random NSArray element in Objective-C

Possible duplicate:
Selecting a random object in NSArray

I have an array in Objective-C with strings:

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

I need a method that takes a random element from an array and returns it. Is there a way, or how can I write it myself? Thank.

+7
arrays random objective-c cocoa nsarray
May 31 '12 at 16:16
source share
2 answers

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 is 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 as follows:

 NSString *randomObject = [tips randomObject]; 

Using a category has another advantage: when you decide to change the way random objects are selected in your application, you simply change the randomObject method.

+39
May 31 '12 at 16:19
source share
 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

+4
May 31 '12 at 16:46
source share



All Articles