【问题标题】:RestKit additional data in responseRestKit 响应中的附加数据
【发布时间】:2014-03-05 18:57:30
【问题描述】:

我正在使用 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
                                          }];

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

【问题讨论】:

    标签: ios objective-c restkit


    【解决方案1】:

    您需要稍微调整映射。如果您按如下方式更改它,您应该能够让 RESTkit 为您解析“someParameter”属性。您需要有两个类(Parent 和 Child)。

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

    代码:

    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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-09-21
        • 2021-05-26
        • 2015-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多