Is there a method to generate a standard 128bit GU

2019-01-31 08:49发布

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 550e8400-e29b-41d4-a716-446655440000 which represents a unique identifier.

7条回答
冷血范
2楼-- · 2019-01-31 09:14

or there's the uuidgen command line tool.

查看更多
3楼-- · 2019-01-31 09:17

Check out the Wikipedia article and the Core Foundation page.

查看更多
淡お忘
4楼-- · 2019-01-31 09:18

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

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-31 09:21

UUIDs are handled in Core Foundation, by the CFUUID library. The function you are looking for is CFUUIDCreate.

FYI for further searches: these are most commonly known as UUIDs, the term GUID isn't used very often outside of the Microsoft world. You might have more luck with that search term.

查看更多
劳资没心,怎么记你
6楼-- · 2019-01-31 09:22

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.

查看更多
萌系小妹纸
7楼-- · 2019-01-31 09:28

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.

查看更多
登录 后发表回答