Pick random element of NSArray in Objective-C [duplicate]

走远了吗. 提交于 2019-11-28 08:38:23

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.

pasawaya
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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!