selecting a random objectAtIndex from NSArray

烂漫一生 提交于 2019-12-06 12:09:11

问题


I have an NSArray which contains 10 objects from index 0 - 9. Each entry in the array is a quotation.

When my user selects the 'random quote' option I want to be able to select a random entry from the array and display the text that is contained in that entry.

Can anyone point me in the right direction on how to achieve this?


回答1:


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];



回答2:


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.




回答3:


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.




回答4:


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];
}


来源:https://stackoverflow.com/questions/7940222/selecting-a-random-objectatindex-from-nsarray

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