【问题标题】:RestKit just for object mappingRestKit 仅用于对象映射
【发布时间】:2014-03-05 19:08:18
【问题描述】:

我正在使用 RestKit 将数据从我的 api 映射到 CoreData 实体,但是当我想以非标准方式使用这个库时遇到了一些困难。比如RestKit additional data in response中描述的

所以我决定使用 AFNetworking + MagicalRecord 并为自己做一些工作。我喜欢 RestKit 对象映射,所以我想使用它。

[afhttpRSClient getPath:@"_api/items"
             parameters:parameters
                success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    if ([responseObject isKindOfClass:[NSDictionary class]]) {
                        id items = responseObject[@"items"];

                        if (items && [items isKindOfClass:[NSArray class]]) {
                            NSManagedObjectContext *context = [NSManagedObjectContext MR_contextForCurrentThread];

                            for (NSDictionary *item in items) {
                                SomeEntity *entity = [SomeEntity MR_findFirstByAttribute:@"entityId" withValue:item[@"id"] inContext:context];

                                if (!entity) {
                                    entity = [SomeEntity MR_createInContext:context];
                                }

                                RKMappingOperation *mappingOperation;
                                mappingOperation = [[RKMappingOperation alloc] initWithSourceObject:item
                                                      destinationObject:entity
                                                                mapping:[SomeEntity entityMapping]];

                                NSError *mappingError = nil;
                                BOOL mappingSuccess = [mappingOperation performMapping:&mappingError];
}

                        }
                    }
                }
                failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"error: %@", error);
                }];

但我想知道是否有任何适当的方法可以使用部分 RestKit 自动将我的 items NSArray 直接绑定到 CoreData?我认为它已经实现了该代码的更常见部分,我想使用它。可以吗?

【问题讨论】:

    标签: objective-c restkit


    【解决方案1】:

    您可以使用RKMappingOperation 做您想做的事,主要是您缺少必需的dataSource(请参阅RKManagedObjectMappingOperationDataSource)。通常,您不会提供目标实体,而是允许 dataSource 创建它(基于映射实体类型)。

    通常最好使用 RestKit 处理要执行映射的请求,并在不需要映射时使用 AFN。其他问题的答案告诉您如何提取“额外”信息。

    【讨论】:

      猜你喜欢
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      相关资源
      最近更新 更多