Created
February 22, 2012 21:48
-
-
Save nsantorello/1887638 to your computer and use it in GitHub Desktop.
Random alphanumeric case-sensitive ID generator in Objective C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! =)