Ward Ward - 10 months ago 82
Objective-C Question

Generate a random alphanumeric string in cocoa

I know this can't be that hard. I've searched, but I can't seem to find a simple solution. I want to call a method, pass it the length and have it generate a random alphanumeric string.

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



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;