我找不到从CBUUID中取回UUID字符串的任何官方方法。这些UUID的长度可以为2或16个字节。
目标是将CBUUIDs作为字符串存储在文件中的某个位置,然后使用[CBUUID UUIDWithString:]等复活。这是到目前为止的内容。
// 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?
}
最佳答案
我为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
对于此输入:
NSLog(@"UUID string: %@", [[CBUUID UUIDWithString:@"0bd51666-e7cb-469b-8e4d-2742f1ba77cc"] representativeString]);
NSLog(@"UUID string2: %@", [[CBUUID UUIDWithString:@"1800"] representativeString]);
它产生以下输出:
UUID string: 0bd51666-e7cb-469b-8e4d-2742f1ba77cc
UUID string2: 1800
并为16字节UUID保留适当的连字符,同时支持简单的2字节UUID。
关于ios - 如何将CBUUID转换为字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13275859/