I have a response descriptor that maps a response using a keyPath such as @"rootKey.subKey"
, where rootKey is a dictionary and subKey is an array. e.g.
{rootKey:{subKey:[@"object1", @"object2",...,]}}
But some times I get the following response:
{rootKey:@""}
And my app crashes with an exception that NSString
isn't key value coding-compliant for the key 'subKey'.
Any ideas how can I handle such situations?
The way I handled it was to create a response descriptor for the top level key, i.e. @"rootKey", instead of @"rootKey.subKey", and created a top level object that only has a single relationship property "subKeys". Then I created a dynamic mapping which based on the representation of the top level objects, either returns a mapping for the subKeys, or nil:
RKEntityMapping *responseMapping = [RKEntityMapping mappingForEntityForName:@"RootObject" inManagedObjectStore:managedObjectStore];
[responseMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"subKeys" toKeyPath:@"subKeys" withMapping:subKeysMapping]];
RKDynamicMapping* dynamicMapping = [RKDynamicMapping new];
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
if ([representation isKindOfClass:[NSDictionary class]]) {
return responseMapping;
}
return nil;
}];
return dynamicMapping;
This leads to having an unnecessary top level object (RootObject) but handles the response gracefully when instead of a key-value object, I get a string.