How to turn CBUUID into string

前端 未结 8 1000
太阳男子
太阳男子 2020-12-28 20:11

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

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 20:54

    I rigged up the following category to do this for CBUUID:

    @interface CBUUID (StringExtraction)
    
    - (NSString *)representativeString;
    
    @end
    
    @implementation CBUUID (StringExtraction)
    
    - (NSString *)representativeString;
    {
        NSData *data = [self data];
    
        NSUInteger bytesToConvert = [data length];
        const unsigned char *uuidBytes = [data bytes];
        NSMutableString *outputString = [NSMutableString stringWithCapacity:16];
    
        for (NSUInteger currentByteIndex = 0; currentByteIndex < bytesToConvert; currentByteIndex++)
        {
            switch (currentByteIndex)
            {
                case 3:
                case 5:
                case 7:
                case 9:[outputString appendFormat:@"%02x-", uuidBytes[currentByteIndex]]; break;
                default:[outputString appendFormat:@"%02x", uuidBytes[currentByteIndex]];
            }
    
        }
    
        return outputString;
    }
    
    @end
    

    For this input:

    NSLog(@"UUID string: %@", [[CBUUID UUIDWithString:@"0bd51666-e7cb-469b-8e4d-2742f1ba77cc"] representativeString]);
    NSLog(@"UUID string2: %@", [[CBUUID UUIDWithString:@"1800"] representativeString]);
    

    it produces the following output:

    UUID string: 0bd51666-e7cb-469b-8e4d-2742f1ba77cc
    UUID string2: 1800
    

    and preserves the appropriate hyphenation for the 16 byte UUIDs, while supporting the simple 2-byte UUIDs.

提交回复
热议问题