Thursday, June 13, 2013

Generate primary key - Objective C

The following code will generate a primary key using the current time stamp, a character (I have used the character 'T' in this example) and a random number. I have used this to generate primary keys for database records.


#include

- (NSString *) getPrimaryKey{

NSDate *curDate = [[NSDate alloc]init];

NSTimeInterval inter = [curDate timeIntervalSince1970]; //return as double
[curDate release];

NSString *str = [NSString stringWithFormat:@"%f",inter];

NSString *mutstr = [str stringByReplacingOccurrencesOfString:@"." withString:@"T"];
mutstr = [NSString stringWithFormat:@"%@%d",mutstr,arc4random_uniform(100)];

return mutstr;
}

No comments: