RestKit ios相同类型的嵌套对象

时间:2013-05-29 08:15:22

标签: ios xml-parsing restkit

如何映射相同类型的嵌套对象? 我有一个xml,其对象可能包含多个相同类型的对象:

<entry location="l1">
    <entry location="l1.1">
        <entry location="l1.1.1">
        </entry>
        <entry location="l1.1.2">
        </entry>
    </entry>
</entry>

如果我添加一个具有相同映射的属性映射,我会得到无限递归:

+ (RKObjectMapping *)objectMapping {
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Entry class]];
    [mapping addAttributeMappingsFromDictionary:@{@"location": @"location"}];
    [mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"nextEntries"
                                                                            toKeyPath:@"entries"
                                                                          withMapping:[Entry objectMapping]]];

    return mapping;
}

是否可以将子对象添加到每个父对象的数组中?

欢呼声

//编辑:以下代码适用于我:

+ (RKObjectMapping *)objectMapping
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Entry class]];
    [mapping addAttributeMappingsFromDictionary:@{@"location": @"location"}];

    RKObjectMapping *innerMapping = [RKObjectMapping mappingForClass:[Entry class]];
    [innerMapping addAttributeMappingsFromDictionary:@{@"location": @"location"}];

    [mapping addPropertyMapping:[RKRelationshipMapping
        relationshipMappingFromKeyPath:@"entry"
        toKeyPath:@"entries"
        withMapping:innerMapping]];

    return mapping;
}

1 个答案:

答案 0 :(得分:2)

我没有尝试过,所以我不知道它是否可行但是试试这个:

+ (RKObjectMapping *)objectMapping
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Entry class]];
    [mapping addAttributeMappingsFromDictionary:@{@"location": @"location"}];

    RKObjectMapping *innerMapping = [RKObjectMapping mappingForClass:[Entry class]];
    [innerMapping addAttributeMappingsFromDictionary:@{@"location": @"location"}];

    [mapping addPropertyMapping:[RKRelationshipMapping
        relationshipMappingFromKeyPath:@"nextEntries"
        toKeyPath:@"entries"
        withMapping:innerMapping]];

    return mapping;
}

不确定toKeyPath:@"entries"是否正确,可能需要toKeyPath:@"entry"根据您的XML。

无限递归是因为你从它自己调用相同的方法([Entry objectMapping]),它与映射无关。