4

I have Parent/child class like this:

@interface Parent : MTLModel <MTLJSONSerializing>
- (void)someMethod;

@property a,b,c...;   // from the JSON    
@property NSArray *childs;  // from the JSON
@end

@interface Child : MTLModel <MTLJSONSerializing>
@property d,e,f,...;    // from the JSON    
@property Parent *parent;   // *not* in the JSON
@end

All the fields a to f are in the JSON, with the same name (hence my JSONKeyPathsByPropertyKey method return nil), and the proper JSONTransformer is correctly setup so that the childs array in parent is containing Child class and not NSDictionary.

Everything work forwardly.

But I want, as a convenience, a property in my Child model that reference back to the parent that own it. So that in the code I can do that:

[childInstance.parent someMethod]

How do I do that with Mantle ??

I want, when the parent is parsing the child's JSON and creating the Child class, to add a ref to itself. (With an init method ??)

Thanks.

malaba
  • 599
  • 5
  • 22

1 Answers1

2

I do this by overriding MTLModel -initWithDictionary:error: method. Something like this.

Child interface:

@interface BRPerson : MTLModel <MTLJSONSerializing>
@property (nonatomic, copy, readonly) NSString *name;
@property (strong, nonatomic) BRGroup *group; // parent
@end

In parent implementation:

- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error {
    self = [super initWithDictionary:dictionaryValue error:error];
    if (self == nil) return nil;

    // iterates through each child and set its parent
    for (BRPerson *person in self.people) {
        person.group = self;
    }
    return self;
}

Techinical note:

If you are curious like me, I already tried to tweak MTLJSONAdapter by changing its forwardBlock and reversibleBlock. But I can't, because those are inside MTLReversibleValueTransformer superclass, and that class is declared privately in "MTLValueTransformer.m". So the initWithDictionary approach above should be much easier.

Hlung
  • 13,850
  • 6
  • 71
  • 90