Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding c-struct with Mantle (NSCoding)

I want to use Mantle framework (https://github.com/github/Mantle) to support NSCoding for my class with struct property:

typedef struct {
    int x;
    int y;
} MPoint;

typedef struct {
    MPoint min;
    MPoint max;
} MRect;


@interface MObject : MTLModel

@property (assign, nonatomic) MRect rect;

@end

@implementation MObject
@end

But when I tried to [NSKeyedArchiver archiveRootObject:obj toFile:@"file"]; its crashed in MTLModel+NSCoding.m, in - (void)encodeWithCoder:(NSCoder *)coder on line

case MTLModelEncodingBehaviorUnconditional:
    [coder encodeObject:value forKey:key];

Does Mantle supports c-struct encoding (and also decoding) or I've need to custom implementing NSCoding protocol for such classes?

like image 810
podkovyr Avatar asked Feb 15 '23 10:02

podkovyr


1 Answers

My original data structure is an XML (yeah, I know):

  ...
  <Lat>32.062883</Lat>
  <Lot>34.782904</Lot>
  ...

I used MTLXMLAdapter based on KissXML, but you can see how it's applicable to any other serializer.

+ (NSValueTransformer *)coordinateXMLTransformer {
    return [MTLValueTransformer reversibleTransformerWithBlock:^id(NSArray *nodes) {
        CLLocationCoordinate2D coordinate;
        for (DDXMLNode *node in nodes) {
            if ([[node name] isEqualToString:@"Lat"]) {
                coordinate.latitude = [[node stringValue] doubleValue];
            } else if ([[node name] isEqualToString:@"Lot"]) {
                coordinate.longitude = [[node stringValue] doubleValue];
            }

        }
        return [NSValue value:&coordinate
                 withObjCType:@encode(CLLocationCoordinate2D)];
    }];
}

You can add a reverseBlock if needed.

like image 80
Sash Zats Avatar answered Feb 17 '23 01:02

Sash Zats