RestKit 0.20命名发布请求

时间:2013-06-04 12:23:15

标签: restkit restkit-0.20

我正在尝试发布一个object1(托管对象)并接收另一个object2(不是托管对象)。 我收到以下错误: W restkit.object_mapping:RKMapperOperation.m:98 Adding mapping error: Expected an object mapping for class of type '<object1 class>', provider returned one for '<object2 class>'

我知道为什么会发生这种错误,但不知道解决方案。

这是我的代码,到目前为止我是如何尝试的:
请求映射:

RKObjectMapping *objectMapping = [RKObjectMapping requestMapping];
[objectMapping addAttributeMappingsFromArray:@[@"prop1", @"prop2", @"prop3"]];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:objectMapping objectClass:[<object1 class> class] rootKeyPath:nil];
[[RKObjectManager sharedManager] addRequestDescriptor:requestDescriptor];

响应映射:

RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[<object2 class> class]];
[objectMapping addAttributeMappingsFromArray:@[@"prop4", @"prop5"]];
responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:objectMapping pathPattern:@"myPattern" keyPath:@"" statusCodes:statusCodes];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];

路由:

[[RKObjectManager sharedManager].router.routeSet addRoute:[RKRoute routeWithClass:[<object1 class> class] pathPattern:@"myPattern" method:RKRequestMethodPOST]];

电话:

[[RKObjectManager sharedManager] postObject:object1 path:nil parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    // Success
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    // Fail
}];

2 个答案:

答案 0 :(得分:2)

如果收到的对象与发送的对象不同,则不能使用postObject:。相反,您需要自己生成请求操作(RKObjectRequestOperation),然后您可以指定传出数据的映射并使用不同的映射处理传入数据。

使用RKObjectManager requestWithObject:生成请求,使用RKObjectRequestOperation initWithRequest:来处理响应。

答案 1 :(得分:1)

我可以确认@Wain的回答是正确的(我要感谢他解决了让我失去3天的问题)。如果要为请求和响应使用不同的对象,则应使用以下内容执行POST请求:

 NSURL *url = [NSURL URLWithString:_baseURL];
    RKObjectManager *restManager = [RKObjectManager managerWithBaseURL:url];   

    NSMutableURLRequest * request = [restManager requestWithObject:_objectToPost method:RKRequestMethodPOST path:_pathPattern parameters:_parameters];
                RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];
                [operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {

                    // process the response
                } failure:^(RKObjectRequestOperation *operation, NSError *error) {

                    // process the error
                }];
    [restManager enqueueObjectRequestOperation:operation];