How to pick a random character from a string in Objective-C

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:

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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.