Imagine we had an NSString consisting of a pool of characters from which we’d like to pick one at random. Say our pool is ABCDEFGHIJKLMNOP, and we want a single character.
Here’s how we can do that:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// pool of characters NSString *characters = @"ABCDEFGHIJKLMNOP"; // create a random number // between 1 and however many characters we have in the pool uint32_t length = (uint32_t)characters.length; NSUInteger random = arc4random_uniform(length); // make a range NSRange range = NSMakeRange(random, 1); // pick a random character from the pool NSString *letter = [characters substringWithRange:range]; |
The comments speak for themselves. One thing of note is the typecast of characters.length, which is needed to suppress the Xcode warning “implicit conversion loses integer precision”.
Most of the magic is provided by the NSString method substringWithRange.