@Darryl’s answer is correct, but could use some minor tweaks:
NSUInteger randomIndex = arc4random() % theArray.count;
Modifications:
- Using
arc4random()
overrand()
andrandom()
is simpler because it does not require seeding (callingsrand()
orsrandom()
). - The modulo operator (
%
) makes the overall statement shorter, while also making it semantically clearer.
Related Contents:
- How to print out the method name and line number and conditionally disable NSLog?
- throwing an exception in objective-c/cocoa
- How do I convert NSMutableArray to NSArray?
- Best way to define private methods for a class in Objective-C
- What is the best way to unit test Objective-C code?
- Objective-C: Extract filename from path string
- Execute a terminal command from a Cocoa app
- Best way to remove from NSMutableArray while iterating?
- What’s the Best Way to Shuffle an NSMutableArray?
- NULL vs nil in Objective-C
- What is the best way to solve an Objective-C namespace collision?
- How does an underscore in front of a variable in a cocoa objective-c class work?
- NSString tokenize in Objective-C
- Remove all whitespaces from NSString
- Is there a way to suppress warnings in Xcode?
- Check whether or not the current thread is the main thread
- How do I make and use a Queue in Objective-C?
- NSString: isEqual vs. isEqualToString
- What exactly is a so called “Class Cluster” in Objective-C?
- How can I dynamically create a selector at runtime with Objective-C?
- Make a two-digit string from a single-digit integer
- View-based NSTableView with rows that have dynamic heights
- Using a constant NSString as the key for NSUserDefaults
- Objective-C: Assertion vs. Exception vs. Error
- Objective-C Introspection/Reflection
- How to compare two dates in Objective-C
- How do I create a NSTimer on a background thread?
- How do I create a Cocoa window programmatically?
- How to get the file size given a path?
- What is the most efficient way to sort an NSSet?
- Class method equivalent of -respondsToSelector:
- How to check the last char of an NSString
- How do I get the current date in Cocoa
- Number of occurrences of a substring in an NSString?
- Get file path and URL for file in temp directory
- Cocoa versus Cocoa Touch – What is the difference?
- Suppressing “‘…’ is deprecated” when using respondsToSelector
- Enable and Disable NSLog in DEBUG mode
- Object allocate and init in Objective C
- Hiding NSTableView header?
- dispatch_sync vs. dispatch_async on main queue
- Reverse NSString text
- Open source Objective-C projects with high quality code?
- How to Write OS X Finder plugin
- Check if an NSString is just made out of spaces
- Avoiding “NSArray was mutated while being enumerated”
- Accessing command line arguments in Objective-C
- How to prevent circular reference when Swift bridging header imports a file that imports Hopscotch-Swift.h itself
- Lightweight migration of a NSPersistentDocument
- 2D arrays using NSMutableArray