Mantle property class based on another property?

a 夏天 提交于 2019-12-03 14:47:27

You can pass the type information by modifying the JSONKeyPathsByPropertyKey method:

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    return @{
        NSStringFromSelector(@selector(content)) : @[ @"type", @"content" ],
    };
}

Then in contentJSONTransformer, you can access the "type" property:

+ (NSValueTransformer *)contentJSONTransformer 
{
    return [MTLValueTransformer ...
        ...
        NSString *type = value[@"type"];
        id content = value[@"content"];
    ];
}
Jane Sales

I've had a similar issue, and I suspect my solution isn't much better than yours.

I have a common base class for my Mantle objects, and after each is constructed, I call a configure method to give them chance to set up properties that are dependent on more than one "base" (== JSON) property.

Like this:

+(id)entityWithDictionary:(NSDictionary*)dictionary {

    NSError* error = nil;
    Class derivedClass = [self classWithDictionary:dictionary];
    NSAssert(derivedClass,@"entityWithDictionary failed to make derivedClass");
    HVEntity* entity = [MTLJSONAdapter modelOfClass:derivedClass fromJSONDictionary:dictionary error:&error];
    NSAssert(entity,@"entityWithDictionary failed to make object");
    entity.raw = dictionary;
    [entity configureWithDictionary:dictionary]; // Give the new entity a chance to set up derived properties
    return entity;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!