Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify child objects type in an NSArray with Mantle

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?

like image 231
Mr Rogers Avatar asked Dec 14 '12 17:12

Mr Rogers


2 Answers

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]; 
like image 174
Mr Rogers Avatar answered Sep 21 '22 15:09

Mr Rogers


+[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.

like image 27
Manuel Binna Avatar answered Sep 20 '22 15:09

Manuel Binna