RestKit 0.2x:如何在应用映射之前检查keyPath是否存在

时间:2013-06-30 06:24:23

标签: iphone objective-c cocoa-touch restkit-0.20

在我的应用中,我做了类似的事情:

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

但是根据某些条件,键inboundInfo可能也可能不会返回JSON,我不想在objectManager添加一个全新的(大)响应描述符但是,为了满足这种情况,有没有办法在添加属性映射之前检查inboundInfo密钥路径是否存在?

P.S。如果inboundInfo未与JSON一起返回,则上述行会导致崩溃,删除应用程序就行了。

编辑:使用RKDynamicMapping解决了这样的问题:

//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;

}];

1 个答案:

答案 0 :(得分:2)

您可以使用RKDynamicMapping运行一个代码块来分析响应并决定您要应用的映射。

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

(动态对象映射部分)https://github.com/RestKit/RestKit/wiki/Object-mapping