How to specify child objects type in an NSArray with Mantle

為{幸葍}努か 提交于 2019-12-03 04:14:28

问题


If I have a dictionary like

{
  name: "Bob",
  cars: [
    { make: "ford", year: "1972" },
    { make: "mazda", year: "2000" }
  ],
}

and two models like:

@interface CarModel : MTLModel

@property (nonatomic, strong) NSString *make;
@property (nonatomic, strong) NSString *year;

@end

@interface PersonModel : MTLModel

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSArray *cars;

@end

How do I use Mantle so that my array of cars in my person model are CarModels?


回答1:


Ah figured it out. I needed to add a private method:

+ (NSValueTransformer *)carsTransformer
{
    return [NSValueTransformer mtl_externalRepresentationArrayTransformerWithModelClass:[CarModel class]];
}

and make sure I used:

[PersonModel modelWithExternalRepresentation:dict];



回答2:


+[NSValueTransformer mtl_externalRepresentationArrayTransformerWithModelClass:] is deprecated. The new API is +[NSValueTransformer mtl_JSONArrayTransformerWithModelClass:].

After switching to the new API, the models can be initialized with the default initializers provided by, e.g., MTLJSONAdapter.




回答3:


A note on:

[NSValueTransformer mtl_JSONArrayTransformerWithModelClass:CarModel.class];

This methods seems to now be deprecated. I'm using this new method in my code and it appears to be working just fine:

[MTLJSONAdapter arrayTransformerWithModelClass:CarModel.class];



回答4:


+ (NSValueTransformer *)carsJSONTransformer {
    return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:CarModel.class];
}

Read more here




回答5:


+[NSValueTransformer mtl_JSONArrayTransformerWithModelClass:]

This method is deprecated. New method is:

  + (NSValueTransformer *)carsTransformer
    {
        return [MTLJSONAdapter arrayTransformerWithModelClass:[CarsModel class]];
    }


来源:https://stackoverflow.com/questions/13883693/how-to-specify-child-objects-type-in-an-nsarray-with-mantle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!