Vincent Gable’s Blog

February 24, 2008

UUID (GUID) Support in Cocoa

Filed under: Cocoa,Objective-C,Programming,UNIX | , ,
― Vincent Gable on February 24, 2008

To easily create a new UUID (aka GUID) in Cocoa, add the following method as a category to NSString:

+ (NSString*) stringWithUUID {
   CFUUIDRef uuidObj = CFUUIDCreate(nil);//create a new UUID
   //get the string representation of the UUID
   NSString *uuidString = (NSString*)CFUUIDCreateString(nil, uuidObj);
   CFRelease(uuidObj);
   return [uuidString autorelease];
}

That’s it, just 4 lines of code. There’s really no need to deal with an entire UUID class. All you ever need to do with UUIDs is create them, compare them, and store/retrieve them. + stringWithUUID handles creation. The string it returns responds to - isEqual:, and is easy to write or read using the mature Foundation APIs. What more could you ask for from a UUID object?

Simpler Ways:

You might only need: [[NSProcessInfo processInfo] globallyUniqueString]. As the name implies, it gives you a UUID that can be used to identify a process.

If you want a UUID without messing with compiled code, the uuidgen command-line tool generates them, or you can use this website.

Powered by WordPress