0

我的班级中有一个 ccColor3B 属性,我想使用 NSCoding 来坚持。我怎样才能做到这一点?NSCoder 似乎没有允许它的方法。

4

3 回答 3

1

@Justin 是正确的,您必须通过字节进行编码,但我认为他想多了:

// encode
ccColor3B input;
[coder encodeBytes:&input length:sizeof(input) forKey:@"color"];

// decode
ccColor3B output;
const uint8_t *bytes = [coder decodeBytesForKey:@"color" returnedLength:NULL];
memcpy(&output, bytes, sizeof(output));
于 2012-05-29T14:17:32.830 回答
0

按字节编码,如下所示:

const NSUInteger BytesInCCColor = 3U;
const uint8_t bytes[BytesInCCColor] = { color.r, color.g, color.b };
[coder encodeBytes:bytes length:BytesInCCColor forKey:@"color"];

解码:

NSUInteger outLength = 0;
const uint8_t* const bytes =
    [coder decodeBytesForKey:@"color" returnedLength:&outLength];

if (NULL == bytes || BytesInCCColor != outLength) {
  …uh-oh…
}
else {
  color.r = bytes[0];
  color.g = bytes[1];
  color.b = bytes[2];
}
于 2012-05-29T14:05:45.013 回答
0

比使用临时类型不安全转换更好的是在 NSCoder 上实现一个类别,该类别了解如何处理它:

@implementation NSCoder (cocos2d)

- (void)encodeUInt32:(uint32_t)i forKey:(NSString *)key {
    union { int32_t s; uint32_t u; } v;
    v.u = i;
    [self encodeInt32:v.s forKey:key];
}

- (uint32_t)decodeUInt32ForKey:(NSString *)key {
    union { int32_t s; uint32_t u; } v;
    v.s = [self decodeInt32ForKey:key];
    return v.u;
}

- (void)encodeColor3B:(ccColor3B)color forKey:(NSString *)key {
    /* Storing 0xFF as the low 8 bits allows us to read/write ccColor3B
       and ccColor4B interchangeably. */
    uint32_t rgba = (color.r << 24) | (color.g << 16) | (color.b << 8) | 0xFF;
    [self encodeUInt32:rgba forKey:key];
}

- (ccColor3B)decodeColor3BForKey:(NSString *)key {
    ccColor3B c;
    uint32_t rgba = [self decodeUInt32ForKey:key];
    c.r = rgba >> 24;
    c.g = rgba >> 16;
    c.b = rgba >> 8;
    return c;
}

@end

然后你可以这样做:

self.color = [decoder decodeColor3BForKey:@"color"];

[encoder encodeColor3B:self.color forKey:@"color"];
于 2012-07-04T13:03:20.070 回答