ios – 如何将CBUUID转换成字符串

前端之家收集整理的这篇文章主要介绍了ios – 如何将CBUUID转换成字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我找不到任何正式的方法来获得一个UUID字符串退出CBUUID.这些UUID可以是2或16字节长.

目标是将CBUUID存储在一个文件中,作为一个字符串,然后用[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.

原文链接:https://www.f2er.com/iOS/336719.html

猜你在找的iOS相关文章