如何对结构体的c数组使用NSCoding? (MKPolyline) [英] How do I using NSCoding for a c-array of structs? (MKPolyline)

查看:84
本文介绍了如何对结构体的c数组使用NSCoding? (MKPolyline)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加NSCoding支持到一个c数组的结构。具体来说,这是 MKPolyline ,即这是我要处理的:

I want to add NSCoding support to an c array of structs. Specifically this is for a subclass of MKPolyline, i.e. this is what I have to work with:

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

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

I发现了如何对个体结构进行编码的良好答案。例如

I found a good answer on how to encode a individual struct. E.g.

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

.... 

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

是否有一个很好的方法来应用这个到ac Array或者我只需要迭代c-array?

Is there a nice way to apply this to a c Array - or will I simply have to iterate over the c-array?

推荐答案

注意:此方法仅在数据不在处理器具有不同的字节序。

Note: This approach only works if the data isn't going between processors with different "endian-ness". It should be safe going from iOS to iOS, certainly if only used on a given device.

您应该能够将C阵列的内存加载到一个 NSData object然后对 NSData 对象进行编码。

You should be able to load the memory for the C-array into an NSData object then encode the NSData object.

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;

这篇关于如何对结构体的c数组使用NSCoding? (MKPolyline)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆