RestKit将unnested关系映射到拥有对象

时间:2013-12-12 14:38:05

标签: ios objective-c core-data restkit restkit-0.20

我正在尝试使用RestKit将照片的GET响应与Core Data中拥有的User对象相关联(即能够在请求后调用user.photos并让它们自动映射)。但是,我不明白如何自动设置它而不是必须从[user setPhotos:...]明确使用RKMappingResult

有没有办法使用映射和响应描述符自动完成此操作?

路线/响应描述符:

RKRoute *userPhotos = [RKRoute routeWithRelationshipName:@"photos" objectClass:[User class] pathPattern:@"/api/v1/photos" method:RKRequestMethodGET];
[[[[APIClient objectManager] router] routeSet] addRoute:userPhotos];

RKResponseDescriptor *photosDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:self.photoMapping   
                                                                                      method:RKRequestMethodGET
                                                                                 pathPattern:nil
                                                                                     keyPath:kJsonPhotos
                                                                                  statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[[APICacheStore sharedStore] objectManager] addResponseDescriptorsFromArray:@[photosDescriptor]];

代码:

+ (void)getPhotosForUser:(User *)user success:(void (^)())success failure:(void (^)(NSString *errorMsg))failure {
  NSAssert(user, @"User must not be nil when we attempt to fetch their photos.");
  [[APIClient objectManager] getObjectsAtPathForRelationship:@"photos" ofObject:user parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    [user setPhotos:[NSSet setWithArray:[mappingResult array]]];
    success();
  } failure:^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
    failure(error.localizedDescription);
  }];
}

原创JSON:

{
  "meta": {
    "total": 2,
    "offset": 0,
    "limit": 10
  },
  "photos": [
    {
      "id": "d8e1ca59-9f50-4963-8e7e-0b0c8de4bed6",
      "name": "Mary at the mall",
      "updated_at": "2013-12-11T10:16:41.000Z",
      "completed_at": null,
      "created_at": "2013-12-11T10:16:41.000Z",
      "image": "images/is9912zh/image.jpeg"
    },
    {
      "id": "1c75273a-7675-43a9-9b62-3d4236439ec6",
      "name": "John at the park",
      "updated_at": "2013-12-11T10:16:41.000Z",
      "completed_at": null,
      "created_at": "2013-12-11T10:16:41.000Z",
      "image": "images/aj92j127/image.jpeg"
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

不包含您​​看似可用的信息以及您发送请求的方式。

如果路径模式为@"/api/v1/photos/##USER_ID##",则路由将为外键映射提供足够的信息。如果返回的JSON具有用户标识,那么将为外键映射提供足够的信息。

从技术上讲,该操作具有填充关系所需的所有信息,但RestKit(目前)没有尝试这样做。您可以查看实现此操作并提交拉取请求。