Implementing object mapping using RestKit in Objective-C
Asked Answered
R

1

0

I am having trouble mapping a JSON response to objects using RestKit and Objective-C.

I have already set up my RKObjectManager and mappings in my AppDelegate as suggested in my previous post by mja.

I call my backend in my controller as per the example below.

There are two issues I'm having trouble with:

  1. [[RKObjectManager sharedManager] postObject:request mapResponseWith:responseMapping delegate:self]; } <-- This results in a "self" is incompatible with type id. What do I need to send to this?
  2. How do I cast the result in didLoadObject to the Translation object I've defined (translationText)

Any help would be much appreciated.

@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);  
}
Ruy answered 29/11, 2011 at 23:47 Comment(0)
H
1

to rectify the first issue, declare your controler in the .h file as follows:

#import "RestKit/RestKit.h"
...
@interface MyController : UIViewController<RKObjectLoaderDelegate>

You cast it just like this:

- (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];
} 

you may update your question with the definition of @properties in your Translation object in order to be sure this answer is correct.

Highborn answered 30/11, 2011 at 0:11 Comment(1)
after re-reading your code i think you should do the following. Declare a retained property on yoyr controller and just assign the 'object' you get in your delegate to the property like this: self.translation = object; then you can access the values later in the class using the self.translation property (getter)Highborn

© 2022 - 2024 — McMap. All rights reserved.