从Array获取随机对象

Son*_*onu 14 iphone arc4random

我想从数组中获取随机对象,有什么方法可以从可变数组中找到随机对象?

zou*_*oul 36

@interface NSArray (Random)
- (id) randomObject;
@end

@implementation NSArray (Random)

- (id) randomObject
{
     if ([self count] == 0) {
         return nil;
     }
     return [self objectAtIndex: arc4random() % [self count]];
}

@end
Run Code Online (Sandbox Code Playgroud)

  • 为了避免模偏差,而不是arc4random()使用arc4random_uniform().(有关更多信息,请参阅http://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator). (2认同)

Ish*_*shu 8

id obj;    
int r = arc4random() % [yourArray count];
    if(r<[yourArray count])
      obj=[yourArray objectAtIndex:r];
   else
   {
     //error message
   }
Run Code Online (Sandbox Code Playgroud)


Vla*_*mir 7

id randomObject = nil;
if ([array count] > 0){
    int randomIndex = arc4random()%[array count];
    randomObject = [array objectAtIndex:randomIndex];
}
Run Code Online (Sandbox Code Playgroud)