1

我想将一个 128 位的 UUID 保存到一个 16 字节的字符串中,它将作为我的 ManagedObject 的索引属性存储在 Core Data 中,以确保插入和选择效率。

有没有办法将 128 位 UUID 存储到 16 字节的 ASCII 字符串中?如果有,如何在 32 字节 UUID 字符串和 16 字节 ASCII 字符串之间进行转换?

我尝试使用下面的代码将 CFUUIDBytes 存储到字符串中,但是在生成字符串后值发生了变化。(如果任何字节值 > 127,则其值在生成的字符串中发生变化)

CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
CFUUIDBytes uuidBytes = CFUUIDGetUUIDBytes(uuidRef);
NSString *utf8String = [NSString stringWithFormat:@"%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c", 
                            uuidBytes.byte0, uuidBytes.byte1, uuidBytes.byte2,
                            uuidBytes.byte3, uuidBytes.byte4, uuidBytes.byte5,
                            uuidBytes.byte6, uuidBytes.byte7, uuidBytes.byte8,
                            uuidBytes.byte9, uuidBytes.byte10, uuidBytes.byte11,
                            uuidBytes.byte12, uuidBytes.byte13, uuidBytes.byte14,
                            uuidBytes.byte15];
4

1 回答 1

0

在 NSString礼貌上使用这个类别:

   static unichar x (unsigned int); 

@implementation NSString (TWUUID) 

+ (NSString*) stringWithUniqueId 
{ 
    CFUUIDRef uuid = CFUUIDCreate(NULL); 
    CFUUIDBytes b = CFUUIDGetUUIDBytes(uuid); 
    unichar unichars[22]; 
    unichar* c = unichars; 
    *c++ = x(b.byte0 >> 2); 
    *c++ = x((b.byte0 & 3 << 4) + (b.byte1 >> 4)); 
    *c++ = x((b.byte1 & 15 << 2) + (b.byte2 >> 6)); 
    *c++ = x(b.byte2 & 63); 
    *c++ = x(b.byte3 >> 2); 
    *c++ = x((b.byte3 & 3 << 4) + (b.byte4 >> 4)); 
    *c++ = x((b.byte4 & 15 << 2) + (b.byte5 >> 6)); 
    *c++ = x(b.byte5 & 63); 
    *c++ = x(b.byte6 >> 2); 
    *c++ = x((b.byte6 & 3 << 4) + (b.byte7 >> 4)); 
    *c++ = x((b.byte7 & 15 << 2) + (b.byte8 >> 6)); 
    *c++ = x(b.byte8 & 63); 
    *c++ = x(b.byte9 >> 2); 
    *c++ = x((b.byte9 & 3 << 4) + (b.byte10 >> 4)); 
    *c++ = x((b.byte10 & 15 << 2) + (b.byte11 >> 6)); 
    *c++ = x(b.byte11 & 63); 
    *c++ = x(b.byte12 >> 2); 
    *c++ = x((b.byte12 & 3 << 4) + (b.byte13 >> 4)); 
    *c++ = x((b.byte13 & 15 << 2) + (b.byte14 >> 6)); 
    *c++ = x(b.byte14 & 63); 
    *c++ = x(b.byte15 >> 2); 
    *c = x(b.byte15 & 3); 
    CFRelease(uuid); 
    return [NSString stringWithCharacters: unichars length: 16];
} 
@end

unichar x (unsigned int c)
{
    if (c < 26) return 'a' + c;
    if (c < 52) return 'A' + c - 26;
    if (c < 62) return '0' + c - 52;
    if (c == 62) return '$';
    return '_';
}


...


    NSLog(@"%u", [[NSString stringWithCString:[[NSString stringWithUniqueId] UTF8String] encoding:NSASCIIStringEncoding] length]);
于 2012-07-06T05:45:42.560 回答