2013-02-16 38 views
2

我想将NSCoding支持添加到c数组结构中。具体而言,这是为了MKPolyline一个子类,即这是我有工作:如何使用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数组?

+0

怎么样'[NSValue值:aPointArray withObjCType:@encode(MKMapPoint [12])]'或者类似的? – 2013-02-16 18:49:03

+0

@ H2CO3此方法在将来的版本中可能不推荐使用。您应该使用'valueWithBytes:objCType:'来代替。 – voromax 2013-02-16 18:54:21

+0

@voromax没有检查文档,只是重复了OP的内容,但是是真的。 – 2013-02-16 18:56:06

回答

4

注意:这种方法只适用于数据不在具有不同“endianness”的处理器之间进行。从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; 
+0

这将很好地打破可移植性(memdumping'float's,呃......) – 2013-02-16 18:52:08

+0

是的,如果Apple开始使用非ARM芯片,那么在大端和小端设备之间可能会出现问题。 – rmaddy 2013-02-16 18:56:15

+0

这种可移植性问题应该是一个问题,还是不太可能造成影响?另外你如何将它从'NSData'转换回'MKMapPoint'数组? – Robert 2013-02-16 18:59:42

相关问题