在Objective-C中使用RESTKIT实现对象映射
-
25-10-2019 - |
题
我很难使用RestKit和Objective-C映射JSON响应对象。
我已经在Appdelegate中设置了我的rkobjectManager和映射 我以前的帖子 经过 MJA.
我叫我的后端 控制器 按照下面的示例。
我有两个问题遇到的问题:
- [rkObjectManager sharedManager] PostObject:请求mapResponseWith:evysemapping委托:self]; } < - 这导致“自我”与类型ID不相容。我需要发送什么?
- 如何将结果施放到我定义的翻译对象(翻译文本)中
任何帮助将非常感激。
@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文件中声明您的控制器如下:
#import "RestKit/RestKit.h"
...
@interface MyController : UIViewController<RKObjectLoaderDelegate>
您就是这样施放的:
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object {
Translation *myTranslation = (Translation*)object;
...
}
或者您可以通过调用适当的选择器来避免演员
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object {
self.translation.text = [[object translatedText] translation];
}
您可以使用翻译对象中@properties的定义更新问题,以确保此答案正确。
不隶属于 StackOverflow