0

I'm using RestKit to make an API call, but one of my property isn't mapping correctly.

Say I have:

// Animal.h
@interface Animal: NSObject

@property (nonatomic, strong) NSArray<Fruit*> favoriteFruits;

@end

with implementation:

// Animal.h
// This class conforms to NSCoding and correctly implements encodeWithCoder and initWithCoder, no problem

I also have a Fruit class with similar NSCoding stuff:

// Fruit.h
@interface Fruit: NSObject

@property (nonatomic, strong) NSString* name;

@end

Here's how I set up my mapping:

[animalMapping addAttributeMappingsFromDictionary:@{
  @"fruits": @"favoriteFruits"
}];

When I make a GET request via RestKit, the JSON I get back is something like this:

{
  "fruits": [
    {
      "name": "banana"
    },
    {
      "name: "apple"
    }
  ]
}

The request was successfully made, but when I check the mapping result, the elements in favoriteFruits array in the Animal class aren't of type Fruit like I expected. They're of type NSDictionary. The values on the NSDictionary are all correct... I just need to them to be converted automagically to Fruit objects...

Not sure if this is relevant, but when I tried this in the debugger:

(lldb) po ((Fruit*)myAnimal.favoriteFruits[0]).name

I get:

error: Execution was interrupted, reason: Attempted to dereference an invalid ObjC Object or send it an unrecognized selector. The process has been returned to the state before expression evaluation.

Thanks for your help.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
7ball
  • 2,183
  • 4
  • 26
  • 61

1 Answers1

0

Realized I never added a correct relationship to the mapping... What I should have done was:

[animalMapping addAttributeMappingsFromDictionary:@{
  // Other attributes go here, but not favoriteFruits
}];

Then add these lines:

RKRelationshipMapping *fruitsRelationship = [RKRelationshipMapping relationshipMappingFromKeyPath:@"fruits" toKeyPath:@"favoriteFruits" withMapping:animalMapping];
[candidateMapping addPropertyMapping: fruitsRelationship];
7ball
  • 2,183
  • 4
  • 26
  • 61