Say I have an array with objects, 1, 2, 3 and 4. How would I pick a random object from this array?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- back button text does not change
- iOS (objective-c) compression_decode_buffer() retu
- how to find the index position of the ARRAY Where
相关文章
- 现在使用swift开发ios应用好还是swift?
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- didBeginContact:(SKPhysicsContact *)contact not in
- Custom Marker performance iOS, crash with result “
- Converting (u)int64_t to NSNumbers
@Darryl's answer is correct, but could use some minor tweaks:
Modifications:
arc4random()
overrand()
andrandom()
is simpler because it does not require seeding (callingsrand()
orsrandom()
).%
) makes the overall statement shorter, while also making it semantically clearer.This is the simplest solution I could come up with:
It's necessary to check
count
because a non-nil
but emptyNSArray
will return0
forcount
, andarc4random_uniform(0)
returns0
. So without the check, you'll go out of bounds on the array.This solution is tempting but is wrong because it will cause a crash with an empty array:
For reference, here's the documentation:
The man page doesn't mention that
arc4random_uniform
returns0
when0
is passed asupper_bound
.Also,
arc4random_uniform
is defined in<stdlib.h>
, but adding the#import
wasn't necessary in my iOS test program.inx is the random number.
where srand() can be anywhere in the program before the random picking function.
Edit: Updated for Xcode 7. Generics, nullability
if you want to cast that to an int, here's the solution for that (useful for when you need a random int from an array of non-sequential numbers, in the case of randomizing an enum call, etc)
Perhaps something along the lines of:
Don't forget to initialize the random number generator (srandomdev(), for example).
NOTE: I've updated to use -count instead of dot syntax, per the answer below.