selecting a random objectAtIndex from NSArray

限于喜欢 提交于 2019-12-04 16:45:52

I'd recommend you use this instead of hardcoding the 10; that way, if you add more quotations, it will work it out automatically, without you needing to change that number.

NSInteger randomIndex = arc4random()%[array count];
NSString *quote = [array objectAtIndex:randomIndex];

Your probably going to want to use arc4random() to pick an object from 0-9. Then, simply do

NSString* string = [array objectAtIndex:randomPicked];

to get the text of the entry.

You can use arc4random()%10 to get an index. There is a slight bias that should not be a problem.

Better yet use arc4random_uniform(10), there is no bias and is even easier to use.

First, get a random number between your bounds, see this discussion and the relevant man pages. Then just index into the array with it.

int random_number = rand()%10; // Or whatever other method.
return [quote_array objectAtIndex:random_number];

Edit: for those who can't properly interpolate from the links or just don't care to read suggested references, let me spell this out for you:

// Somewhere it'll be included when necessary, 
// probably the header for whatever uses it most.
#ifdef DEBUG 
#define RAND(N) (rand()%N)
#else 
#define RAND(N) (arc4random()%N)
#endif

...

// Somewhere it'll be called before RAND(), 
// either appDidLaunch:... in your application delegate 
// or the init method of whatever needs it.
#ifdef DEBUG
// Use the same seed for debugging 
// or you can get errors you have a hard time reproducing.
srand(42);
#else
// Don't seed arc4random()
#endif

....

// Wherever you need this.
NSString *getRandomString(NSArray *array) {
    #ifdef DEBUG
    // I highly suggest this, 
    // but if you don't want to put it in you don't have to.
    assert(array != nil);
    #endif
    int index = RAND([array count]);
    return [array objectAtIndex:index];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!