RestKit RKObjectMapping Swift More

I have a quick model called Activity that can have a coordinate attached to it.

 import MapKit class Activity: NSObject { var coordinate: CLLocationCoordinate2D? class func objectMapping() -> RKObjectMapping { let mapping = RKObjectMapping(forClass: self) let coordinateMapping = RKAttributeMapping(fromKeyPath: "coordinate", toKeyPath: "coordinate") coordinateMapping.valueTransformer = RKCLLocationCoordinate2DValueTransformer() mapping.addPropertyMapping(coordinateMapping) return mapping } } 

When running my application, however, it gives me:

2015-05-05 12: 14: 30.741 Sample [54338: 531558] *** Application termination due to the uncaught exception "NSUnknownKeyException", reason: "[setValue: forUndefinedKey:]: this class is not a key encoding code- compatible for key coordinates.

If I change the coordinate as optional and deliver by default the application starts.

So my question is how to use RestKit in swift in relation to Optionals?

+7
ios swift restkit
source share
2 answers

Make your property dynamic

 dynamic var coordinate: CLLocationCoordinate2D? 
0
source share

In my opinion, your application crashes due to these lines

let mapping = RKObjectMapping(forClass: self) let coordinateMapping = RKAttributeMapping(fromKeyPath: "coordinate", toKeyPath: "coordinate")

You want to map an optional property / variable, but it may be that when you call objectMapping() , your coordinate is zero.

Have you tried something like this:

 import MapKit class Activity: NSObject { var coordinate: CLLocationCoordinate2D? class func objectMapping() -> RKObjectMapping { if let c = self. coordinate { let mapping = RKObjectMapping(forClass: self) let coordinateMapping = RKAttributeMapping(fromKeyPath: "coordinate", toKeyPath: "coordinate") coordinateMapping.valueTransformer = RKCLLocationCoordinate2DValueTransformer() mapping.addPropertyMapping(coordinateMapping) return mapping } return nil } } 

I'm not sure if this works, but I think let mapping = RKObjectMapping(forClass: self) trying to display your entire Activity class, and this will crash your code when coordinate not set at this time.

-one
source share

All Articles