Ward Ward - 6 months ago 29
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?

Thanks,
Howie

Answer

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;
}
Comments