I can't find any official way to get a UUID string back out of a CBUUID. These UUIDs can be 2 or 16 bytes long.
The goal is to store CBUUIDs in a file somewhere as a string, and then resurrect with [CBUUID UUIDWithString:] etc. Here is what I have so far.
// returns a simple 4 byte string for 16bit uuids, 128 bit uuids are in standard 8-4-4-4-12 format
// the resulting string can be passed into [CBUUID UUIDWithString:]
+(NSString*)CBUUIDToString:(CBUUID*)cbuuid;
{
NSData* data = cbuuid.data;
if ([data length] == 2)
{
const unsigned char *tokenBytes = [data bytes];
return [NSString stringWithFormat:@"%02x%02x", tokenBytes[0], tokenBytes[1]];
}
else if ([data length] == 16)
{
NSUUID* nsuuid = [[NSUUID alloc] initWithUUIDBytes:[data bytes]];
return [nsuuid UUIDString];
}
return [cbuuid description]; // an error?
}
The following Worked me without any error:
iOS 7.1 (beta released yesterday, 11/18/13) introduced the following property on
CBUUID
:From CBUUID Class Reference.
It's also worth noting that for comparing a UUID string with a
CBUUID
, this works:I rigged up the following category to do this for CBUUID:
For this input:
it produces the following output:
and preserves the appropriate hyphenation for the 16 byte UUIDs, while supporting the simple 2-byte UUIDs.
Brad's answer does its work, but the solution could be simpler (though probably not more efficient) using
NSUUID
class:To all those saying that CBUUID is toll-free bridged with CFUUIDRef, it's not.
It's not crashing but you're getting garbage out. It's probably uniquely identifying garbage, but it can't be round-tripped.
PS: This didn't work as a comment because SO comments oddly don't allow code formatting.
I know it's been 7 month since it was asked and answered, but...
CBUUID
is “toll-free bridged” toCFUUID
and the easiest way to convert is