Vincent Gable

February 24, 2008

UUID (GUID) Support in Cocoa

Filed under: Cocoa, Objective-C, Programming — Vincent Gable @ 10:28 pm

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

+ (NSString*) stringWithNewUUID{
   CFUUIDRef uuidObj = CFUUIDCreate(nil);//create a new UUID
   //get the string representation of the UUID
   NSString *newUUID = (NSString*)CFUUIDCreateString(nil, uuidObj);
   CFRelease(uuidObj);
   return [newUUID 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. + stringWithNewUUID 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?

You might also be interested to know about: [[NSProcessInfo processInfo] globallyUniqueString]. As the name implies, it gives you a GUID that can be used to identify a process.

1 Comment »

  1. 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

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress