【问题标题】:How do I using NSCoding for a c-array of structs? (MKPolyline)如何将 NSCoding 用于结构的 c 数组? (MK折线)
【发布时间】:2013-02-16 18:39:59
【问题描述】:

我想将 NSCoding 支持添加到 c 结构数组。具体来说,这是MKPolyline 的子类,即这是我必须使用的:

@property (nonatomic, readonly) MKMapPoint *points;
@property (nonatomic, readonly) NSUInteger pointCount;

+ (MKPolyline *)polylineWithPoints:(MKMapPoint *)points count:(NSUInteger)count;

I found a good answer on how to encode a individual struct。例如

NSValue* point = [NSValue value:&aPoint withObjCType:@encode(MKMapPoint)];
[aCoder encodeObject:point forKey:@"point"];

.... 

NSValue* point = [aDecoder decodeObjectForKey:@"point"];
[endCoordinateValue getValue:&aPoint];

有没有一种很好的方法可以将它应用到 c 数组 - 还是我只需要遍历 c 数组?

【问题讨论】:

  • [NSValue value:aPointArray withObjCType:@encode(MKMapPoint[12])] 或类似的怎么样?
  • @H2CO3 在未来的版本中可能会弃用此方法。你应该改用valueWithBytes:objCType:
  • @voromax 没有检查文档,只是重复了 OP 的内容,但确实如此。

标签: ios objective-c cocoa-touch nscoding


【解决方案1】:

注意:这种方法仅适用于数据不在具有不同“字节序”的处理器之间传输的情况。从 iOS 到 iOS 应该是安全的,当然如果只在给定的设备上使用的话。

您应该能够将 C 数组的内存加载到 NSData 对象中,然后对 NSData 对象进行编码。

MKMapPoint *points = self.points;
NSData *pointData = [NSData dataWithBytes:points length:self.pointCount * sizeof(MKMapPoint)];
[aCoder encodeObject:pointData forKey:@"points"];

更新:取回数据:

NSData *pointData = [aCode decodeObjectForKey:@"points"];
MKMapPoint *points = malloc(pointData.length);
memcpy([pointData bytes], points);
self.points = points;

【讨论】:

  • 这会很好地破坏可移植性(memdumping floats, ehh...)
  • 是的,如果 Apple 开始使用非 ARM 芯片,那么大端和小端设备之间可能会出现问题。
  • 这个可移植性问题应该引起关注,还是不太可能造成影响?另外,您如何将其从 NSData 转换回 MKMapPoint 数组?
  • 我又有点卡住了......我提出了一个新问题。 stackoverflow.com/q/14914265/296446
  • 由于某种原因这对我不起作用,它还给了我一个关于将 const void* 发送到 void* 参数的警告。我使用以下方法修复了它:[pointData getBytes:& points length:pointsSize];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
相关资源
最近更新 更多