使用Objective-C建立UUID

88497010 2012-07-12

UUID是128位的值,它可以保证唯一性。通常,它是由机器本身网卡的MAC地址和当前系统时间来生成的。

UUID是由中划线连接而成的字符串。例如:13222F23-C76A-7781-0C12-0293E3B34398.

下面这个方法可以生成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);
 
  // 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;
}

相关推荐