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 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];
Is there a nice way to apply this to a c Array - or will I simply have to iterate over the c-array?
rmaddy
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.
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"];
Update: to get the data back:
NSData *pointData = [aCode decodeObjectForKey:@"points"];
MKMapPoint *points = malloc(pointData.length);
memcpy([pointData bytes], points);
self.points = points;
来源:https://stackoverflow.com/questions/14913744/how-do-i-using-nscoding-for-a-c-array-of-structs-mkpolyline