JAHelia
JAHelia

Reputation: 7902

RestKit 0.2x : how to check for the existence of a keyPath before applying the mapping

In my app I do something like this:

[itineraryMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"inboundInfo" toKeyPath:@"inboundInfo" withMapping:flightInfoMapping]];

but the key inboundInfo may and may not return with the JSON according to some criteria, I don't want to add a whole new (big) response descriptor to the objectManager to satisfy this case, however, is there a way to check that the inboundInfo key path exists or not before adding the property mapping ?

p.s. in case inboundInfo didn't return with the JSON the above line will make a crash, removing the line the app will be fine.

EDIT: solved using RKDynamicMapping like this:

//configuring the dynamic mapping
[dynamicMapping setObjectMappingForRepresentationBlock:^RKEntityMapping *(id representation) {

    if([[representation objectForKey:@"inboundInfo"] isKindOfClass:[NSDictionary class]]) {
        if(![itineraryMapping.propertyMappings containsObject:inboundInfoMapping]) { //to prevent adding inboundInfoMapping more than once
            [itineraryMapping addPropertyMapping:inboundInfoMapping];
        }
    }

    //if inboundInfo is not a dictionary simply return the itineraryMapping without adding inboundInfoMapping on it
    return itineraryMapping;

}];

Upvotes: 1

Views: 334

Answers (1)

Wain
Wain

Reputation: 119031

You can use RKDynamicMapping to run a block of code which analyses the response and decides which mapping you wish to apply.

http://restkit.org/api/latest/Classes/RKDynamicMapping.html

(Dynamic Object Mapping section) https://github.com/RestKit/RestKit/wiki/Object-mapping

Upvotes: 2

Related Questions