4

我有这样的父/子类:

@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

a 到 f 的所有字段都在 JSON 中,具有相同的名称(因此我的 JSONKeyPathsByPropertyKey 方法返回 nil),并且正确设置了正确的 JSONTransformer,以便 parent 中的 childs 数组包含 Child 类而不是 NSDictionary。

一切都在向前推进

但为了方便起见,我希望在我的 Child 模型中引用拥有它的父级的属性。所以在代码中我可以做到这一点:

[childInstance.parent someMethod]

我如何用 Mantle 做到这一点?

我希望,当父级解析孩子的 JSON 并创建 Child 类时,为其自身添加一个 ref。(使用 init 方法??)

谢谢。

4

1 回答 1

2

我通过覆盖MTLModel -initWithDictionary:error:方法来做到这一点。像这样的东西。

子接口:

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

在父实现中:

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

技术说明:

如果您像我一样好奇,我已经尝试MTLJSONAdapter通过更改其forwardBlockand来进行调整reversibleBlock。但我不能,因为它们在MTLReversibleValueTransformer超类中,并且该类在"MTLValueTransformer.m"中私下声明。所以initWithDictionary上面的方法应该容易得多。

于 2015-09-16T08:26:35.720 回答