Picking a Random Object in an NSArray

@Darryl’s answer is correct, but could use some minor tweaks:

NSUInteger randomIndex = arc4random() % theArray.count;

Modifications:

  • Using arc4random() over rand() and random() is simpler because it does not require seeding (calling srand() or srandom()).
  • The modulo operator (%) makes the overall statement shorter, while also making it semantically clearer.

Leave a Comment