gpt4 book ai didi

ios - 如何使用 Mantle 添加与父级的关系?

转载 作者:可可西里 更新时间:2023-11-01 05:53:46 28 4
gpt4 key购买 nike

我有这样的父/子类:

@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,以便父级中的子数组包含子类而不是 NSDictionary。

一切都向前

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

[childInstance.parent someMethod]

我如何使用 Mantle 做到这一点??

我想,当父级解析子级的 JSON 并创建子级时,为自身添加一个 ref。 (用一个初始化方法??)

谢谢。

最佳答案

我通过覆盖 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;
}

技术说明:

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

关于ios - 如何使用 Mantle 添加与父级的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019938/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com