BlackMouse
BlackMouse

Reputation: 4552

Generate a unique string

I found this answer in another post, on how to generate a random number:

-(NSString *) genRandStringLength:(int)length 
 {
  NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";


NSMutableString *randomString = [NSMutableString stringWithCapacity: length];

for (int i = 0; i < length; i++) {
    [randomString appendFormat: @"%c", [letters characterAtIndex: rand()%[letters     length]]];
}

return randomString;
 }

I building a game and need to generate a unique id for each match. If I have 100,000 new matches a day (when a game is done, it's deleted and its unique id can be reused), what would be safe length to use in the code above, to make sure there won't be any conflicts (2 matches with the same id)? Or is there a better way to generate a unique id?

I want to try to keep the length down for performance, since it will be sent back and forth to the server.

Thanks

Upvotes: 1

Views: 181

Answers (1)

mleonard87
mleonard87

Reputation: 324

Why not use a UUID, this should be a globally unique across the world (within reason - certainly fine for you situation as chances of collision are incredibly low).

An Objective-C example can be found here.

Upvotes: 5

Related Questions