RestKit附加数据作为回应

时间:2014-03-05 18:57:30

标签: ios objective-c restkit

我正在使用RestKit将数据从我的api映射到CoreData实体,我想知道如何从响应中获取其他数据。例如我的api返回结构如:

{
    "items": [
        {
            "id": 1,
            "title": "Title"
        },
        {
            "id": 2,
            "title": "Title 2"
        }
    ],
    "someParameter": "someValue"
}

我已经有了共享对象管理器的正确映射,所以我只发送请求:

[[RKObjectManager sharedManager] getObjectsAtPath:@"_api/items"
                                       parameters:parameters
                                          success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                              //handle success
                                          }
                                          failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                              //handle error
                                          }];

如何在someParameter块中获得success值?这可能吗?

2 个答案:

答案 0 :(得分:2)

您需要略微调整您的映射。如果您按如下方式更改它,您应该能够让RESTkit为您解析'someParameter'属性。你需要有两个班级(父母和孩子)。

Parent类有2个属性(someParameter和一个Child对象数组)。 addRelationshipMappingWithSourceKeyPath将Parent和Child对象映射绑定在一起。

代码:

RKObjectMapping *parentMapping = [RKObjectMapping mappingForClass:[Parent class]];
[beaconActionMapping addAttributeMappingsFromDictionary:@{
                                                          @"someParameter" : @"someParameter"
                                                         }];


RKObjectMapping *childMapping = [RKObjectMapping mappingForClass:[Child class]];
[beaconMapping addAttributeMappingsFromDictionary:@{
                                                  @"id" : @"childId",
                                                  @"title" : @"title"
                                                  }];


[parentMapping addRelationshipMappingWithSourceKeyPath:@"items" mapping:childMapping];

类层次结构:

@interface Parent : NSObject
@property(nonatomic,strong) NSString *someParameter;
@property(nonatomic,strong) NSArray *items;  // Array of Child objects
@end

@interface Child : NSObject
@property(nonatomic,strong) NSString *childId;
@property(nonatomic,strong) NSString *title
@end

答案 1 :(得分:0)

您可以添加其他响应描述符,其关键路径为someParameter。您可以使用nil键路径映射将字符串值提取到您选择的对象中(通常是自定义类)。