Is there a method to generate a standard 128bit GUID (UUID) on the Mac?

后端 未结 7 916
花落未央
花落未央 2020-12-23 21:31

Is there a built in function equivalent to .NET\'s

Guid.NewGuid();

in Cocoa?

My desire is to produce a string along the lines of

相关标签:
7条回答
  • 2020-12-23 22:13

    Some code:

    For a string UUID, the following class method should do the trick:

    +(NSString*)UUIDString {
        CFUUIDRef theUUID = CFUUIDCreate(NULL);
        CFStringRef string = CFUUIDCreateString(NULL, theUUID);
        CFRelease(theUUID);
        return [(NSString *)string autorelease];
    }
    

    if you really want the bytes (not the string):

    +(CFUUIDBytes)UUIDBytes {
        CFUUIDRef theUUID = CFUUIDCreate(NULL);
        CFUUIDBytes bytes = CFUUIDGetUUIDBytes(theUUID);
        CFRelease(theUUID);
        return bytes;
    }
    

    where CFUUIDBytes is a struct of the UUID bytes.

    0 讨论(0)
  • 2020-12-23 22:13

    At least on MacOSX 10.5.x you might use the command line tool "uuidgen" to get your string e.g.

    $ uuidgen

    054209C4-3873-4679-8104-3C18AE780512

    there's also an option -hdr with this comand that conveniently generates it in header style

    See man-page for further infos.

    0 讨论(0)
  • 2020-12-23 22:18

    or there's the uuidgen command line tool.

    0 讨论(0)
  • 2020-12-23 22:20

    Since 10.8 you could also use: NSString *uuidString = [[NSUUID UUID] UUIDString];

    0 讨论(0)
  • 2020-12-23 22:20

    Check out the Wikipedia article and the Core Foundation page.

    0 讨论(0)
  • 2020-12-23 22:27

    Since 10.3 or so, you can use [[NSProcessInfo processInfo] globallyUniqueString]. However, while this currently generates a UUID, it never has been and still isn't guaranteed to do that, so if you really need a UUID and not just any unique string, you should use CFUUID.

    0 讨论(0)
提交回复
热议问题