在 Objective-C 中使用 RestKit 实现对象映射 [英] Implementing object mapping using RestKit in Objective-C
本文介绍了在 Objective-C 中使用 RestKit 实现对象映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法使用 RestKit 和 Objective-C 将 JSON 响应映射到对象.
I am having trouble mapping a JSON response to objects using RestKit and Objective-C.
我按照下面的示例在我的控制器中调用我的后端.
I call my backend in my controller as per the example below.
我遇到了两个问题:
- [[RKObjectManager sharedManager] postObject:request mapResponseWith:responseMapping delegate:self];} <-- 这会导致self"与类型 id 不兼容.我需要向这里发送什么信息?
- 如何将 didLoadObject 中的结果转换为我定义的 Translation 对象 (translationText)
任何帮助将不胜感激.
@synthesize inputtext = _text;
@synthesize translation = _translation;
@synthesize translatedText = _translatedText;
- (Translation *)translatedText {
if (!_translatedText) _translatedText = [[Translation alloc] init];
return _translatedText; }
- (IBAction)translatePressed {
//create TranslationRequest
TranslationRequest *request = [[TranslationRequest alloc] init];
[request setSourceId:@"1"];
[request setRegionTag:@"Hello"];
[request setInputString:self.inputtext.text];
//fetch the desired mapping to map response with
RKObjectMapping * responseMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[Translation class]];
[[RKObjectManager sharedManager] postObject:request mapResponseWith:responseMapping delegate:self]; }
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object {
self.translation.text = [object translatedText].translation;
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error {
NSLog(@"Hit error: %@", error);
}
推荐答案
为了纠正第一个问题,在 .h 文件中声明你的控制器如下:
to rectify the first issue, declare your controler in the .h file as follows:
#import "RestKit/RestKit.h"
...
@interface MyController : UIViewController<RKObjectLoaderDelegate>
你就这样投射:
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object {
Translation *myTranslation = (Translation*)object;
...
}
或者您可以通过调用适当的选择器来避免强制转换
or you can avoid the cast by calling appropriate selector
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object {
self.translation.text = [[object translatedText] translation];
}
您可以使用 Translation 对象中 @properties 的定义更新您的问题,以确保此答案正确.
you may update your question with the definition of @properties in your Translation object in order to be sure this answer is correct.
这篇关于在 Objective-C 中使用 RestKit 实现对象映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文