Generate a random alphanumeric string in Cocoa

Ward picture Ward · Apr 14, 2010 · Viewed 92.3k times · Source

I want to call a method, pass it the length and have it generate a random alphanumeric string.

Are there any utility libraries out there that may have a bunch of these types of functions?

Answer

Jeff B picture Jeff B · Apr 14, 2010

Here's a quick and dirty implementation. Hasn't been tested.

NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

-(NSString *) randomStringWithLength: (int) len {

    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];

    for (int i=0; i<len; i++) {
         [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform([letters length])]];
    }

    return randomString;
}