How to generate a unique identifier?

Centurion picture Centurion · Aug 10, 2011 · Viewed 29.9k times · Source

I need to generate some int value that would never repeat (at least theoretically). I know there is arc4random() fnc but I'm not sure how to use it with some current date or smth :(

Answer

Nandakumar R picture Nandakumar R · Aug 11, 2011

This returns a unique key very similar to UUID generated in MySQL.

+ (NSString *)uuid
{
    CFUUIDRef uuidRef = CFUUIDCreate(NULL);
    CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
    CFRelease(uuidRef);
    return [(NSString *)uuidStringRef autorelease];
}

ARC version:

+ (NSString *)uuid
{
    CFUUIDRef uuidRef = CFUUIDCreate(NULL);
    CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
    CFRelease(uuidRef);
    return (__bridge_transfer NSString *)uuidStringRef;
}