Pick random element of NSArray in Objective-C [dup

2019-01-17 23:37发布

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.

2条回答
我命由我不由天
2楼-- · 2019-01-17 23:54

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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-17 23:54
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

查看更多
登录 后发表回答