在RestKit中映射数组元素计数

时间:2014-12-04 14:56:33

标签: objective-c json collections restkit

我正在使用RestKit 0.23。

考虑以下带有JSON正文的HTTP响应

{
    id: 1,
    description: "abc",
    images: [
        {
            id: 1,
            ... a lot of other attributes that I do not need in fact ...
        }
    ]
}

我定义了以下映射

RKObjectMapping *responseImageMapping = [RKObjectMapping mappingForClass: [NoteImage class]];
[responseImageMapping addAttributeMappingsFromDictionary: @{@"id": @"imageId"}];

RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass: [Note class]];
[responseMapping addAttributeMappingsFromDictionary: @{@"id": @"noteId",
                                                       @"description": @"noteDescription"}];
[responseMapping addPropertyMapping: [RKRelationshipMapping relationshipMappingFromKeyPath: @"images" toKeyPath: @"images" withMapping: responseImageMapping]];

此代码工作正常。 但是,响应包含的数据远远超出我的实际需要。我对图像的任何属性都不感兴趣。我只需要区分空的图像数组和非空的图像数组。

如果我只需要知道图像数组是否为空,我是否必须定义类NoteImage及其映射?

我想知道我是否可以写一些类似

的内容
[responseMapping addAttributeMappingsFromDictionary: @{@"images#isEmpty": @"imagesEmpty"}];

[responseMapping addAttributeMappingsFromDictionary: @{@"images#count": @"imageCounty"}];

感谢。

1 个答案:

答案 0 :(得分:0)

我没试过这个,但是你应该有2个选项,都使用KVC:

最好是collection operators,因此您可以使用@"images.@count" : @"imageCount"

Alternate是使用自定义访问器方法,将整个图像数组传递给它并允许它进行计数(或者做其他事情,比如随机选择一个项目)@"images" : @"countImages"

(请注意,在自定义访问器方法方法中,您需要定义一个setter和一个getter,即使您永远不会使用getter)