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.
thanks so much. This not only got me what I needed but familiarized me with the UUID class and appropriately attaching categories
Comment by Rusty — September 4, 2008 @ 5:56 pm
In accordance with the Create Rule, it should really be called “stringWithRandomUUID” or something else– it’s autoreleased, but “New” in the name would imply that the caller owns the object.
Comment by Adam — November 24, 2008 @ 8:11 pm
Good catch Adam, I’ve changed the name, thanks!
Comment by Vincent Gable — November 24, 2008 @ 9:49 pm