Create a Universally Unique Identifier (UUID)

UUID’s are 128-bit values which are guaranteed to be unique – typically the value is based on a machines ethernet address combined with the current time since October 15, 1582.

UUID’s are string values separated by hyphens, for example, here is how a UUID may look: 13222F23-C76A-7781-0C12-0293E3B34398.

The method below creates a UUID and returns a string representation of the same:

 

Create UUID
- (NSString *)createUUID
{
  // Create universally unique identifier (object)
  CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
 
  // Get the string representation of CFUUID object.
  NSString *uuidStr = [(NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject) autorelease];
 
  // If needed, here is how to get a representation in bytes, returned as a structure
  // typedef struct {
  //   UInt8 byte0;
  //   UInt8 byte1;
  //   ...
  //   UInt8 byte15;
  // } CFUUIDBytes;
  CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuidObject);
 
  CFRelease(uuidObject);
 
  return uuidStr;
}
  1. I thought they weren’t guaranteed to be unique if you create multiple items within a second(or shorter) of each other. this can be a problem.

  2. Here’s the excerpt from the documentation on this method:

    “This method generates a new string each time it is invoked, so it also uses a counter to guarantee that strings created from the same process are unique.”

  3. Unfortunately, this method leaks. CFUUIDCreateString creates a new object and it’s never released. While the CFString and NSString types are toll-free bridged, they don’t share the same reference counting mechanism. So you have to truly convert the result to an NSString to support the retain/release methods.

    +(NSString*) uuid
    {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFStringCreateCopy( NULL, uuidString);
    CFRelease(puuid);
    CFRelease(uuidString);

    return [result autorelease];
    }

    • Thanks Paul. I’ve also updated the original code example to include an autorelease of the string.

  4. for CFUUID, which framework and header files need to be included/import in project?

Comments are closed.