代码之家  ›  专栏  ›  技术社区  ›  TimM

如何在Objective-C中编码/解码CFUUIDRef

  •  3
  • TimM  · 技术社区  · 15 年前

    CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuid);
    eencoder encodeBytes: &bytes length: sizeof(bytes)];
    

    对于解码,我会更加困惑:

    NSUInteger blockSize;
    const void* bytes = [decoder decodeBytesForKey: kFieldCreatedKey returnedLength:&blockSize];
    if(blockSize > 0) {
         uuid = CFUUIDCreateFromUUIDBytes(NULL, (CFUUIDBytes)bytes);
    }
    

    我忽略了上面的错误“转换为非定标器类型”-我已经尝试了几次从我在网上看到的代码位的化身。有人能给我指出正确的方向吗? 提姆

    3 回复  |  直到 15 年前
        1
  •  2
  •   kennytm    15 年前

    更简单(但效率稍低)的方法是将其存储为 NSString ( CFString CFUUIDCreateString ,并使用 CFUUIDCreateFromString .

        2
  •  2
  •   Eyal Redler    15 年前

    代码的问题是解码的最后一行,“bytes”是指向CFUUIDBytes结构的指针,您试图将其转换为CFUUIDBytes结构本身,这是不正确的,并且被编译器正确检测到。尝试将最后一行更改为:

    uuid = CFUUIDCreateFromUUIDBytes(NULL, *((CFUUIDBytes*)bytes));
    

    这里的想法是将“bytes”强制转换为指向CFUUIDBytes的指针(内括号),然后取消引用强制转换的指针(外括号)。严格来说,外括号不是必需的,但我使用它们使表达更清楚。

        3
  •  0
  •   TimM    15 年前

    根据给出的答案,我尝试了Eyal给出的铸造方法,以及Rob提出的NSData方法,我认为后者似乎更清晰,尽管我对其他人的想法感兴趣。

    我最终得出以下结论:

    - (void)encodeWithCoder:(NSCoder *)encoder {  
        // other fields encoded here
        CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuid);
        NSData* data  = [NSData dataWithBytes: &bytes length: sizeof(bytes)];
        [encoder encodeObject: data forKey: kFieldUUIDKey];
    }
    
    - (id)initWithCoder:(NSCoder *)decoder {
        if (self = [super init]) { 
            // other fields unencoded here
            NSData* data = [decoder decodeObjectForKey: kFieldUUIDKey];
            if(data) {
              CFUUIDBytes uuidBytes;
              [data getBytes: &uuidBytes];
              uuid = CFUUIDCreateFromUUIDBytes(NULL,uuidBytes);
        } else {
              uuid = CFUUIDCreate(NULL);
            }
        }
      }