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 が正しく設定されているため、親の子配列には NSDictionary ではなく子クラスが含まれます。

すべてが前向きに働きます。

しかし、便宜上、それを所有する親を参照するChildモデルのプロパティが必要です。そのため、コードで次のことができます。

[childInstance.parent someMethod]

マントルでそれを行うにはどうすればよいですか??

親が子の 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変更して微調整しようforwardBlockとしましreversibleBlockた。しかし、それらはMTLReversibleValueTransformerスーパークラス内にあり、そのクラスは"MTLValueTransformer.m"でプライベートに宣言されているため、できません。したがって、initWithDictionary上記のアプローチははるかに簡単なはずです。

于 2015-09-16T08:26:35.720 に答える