Skip to content

Instantly share code, notes, and snippets.

@nsantorello
Created February 22, 2012 21:48
Show Gist options
  • Save nsantorello/1887638 to your computer and use it in GitHub Desktop.
Save nsantorello/1887638 to your computer and use it in GitHub Desktop.
Random alphanumeric case-sensitive ID generator in Objective C
//
// IdGenerator.h
//
//
// Created by Noah Santorello on 2/22/12.
// Copyright (c) 2012 Noah Santorello. All rights reserved.
//
@interface IdGenerator : NSObject
// Generates a string containing 0-9, A-Z, a-z of the specified length
+(NSString*)randomId:(int)length;
@end
//
// IdGenerator.m
//
//
// Created by Noah Santorello on 2/22/12.
// Copyright (c) 2012 Noah Santorello. All rights reserved.
//
#import "IdGenerator.h"
@implementation IdGenerator
+(NSString*)randomId:(int)length
{
char bytes[length+1];
for (int i = 0; i < length; i++)
{
int place = arc4random() % 62;
place = place < 0 ? -place : place;
if (place < 10)
{
// For 0-9
bytes[i] = place + '0';
}
else if (place < 36)
{
// For A-Z
bytes[i] = place + 'A' - 10;
}
else
{
// For a-z
bytes[i] = place + 'a' - 36;
}
}
bytes[length] = 0;
return [NSString stringWithCString:bytes encoding:NSASCIIStringEncoding];
}
@end
@nsantorello
Copy link
Author

Generates a string consisting of 0-9, A-Z, and a-z of the specified length.

[IdGenerator randomId] yields an ID like JC9zB7ItAU or oYjmJ1BqDb.

@bliang
Copy link

bliang commented Feb 22, 2012

Nice! =)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment