I am facing the following problem..
I have a class Menu.h and Item.h. Menu is like a menu of a restaurant and has multiple categories (like appetizers, salads, etc) and each menu has multiple items associated. So Menu.h has an NSArray property called itemList. I am trying to automatically load these objects using Mantle.
Menu.h
@interface Menu : MTLModel <MTLJSONSerializing>
@property (nonatomic) NSArray *itemList;
@end
And
Menu.m
@implementation Menu
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
// model_property_name : json_field_name
return @{
};
}
+ (NSValueTransformer *)itemListJSONTransformer {
return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass: Item.class];
}
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error {
self = [super initWithDictionary:dictionaryValue error:error];
if (self == nil) return nil;
return self;
}
And
Item.m
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error {
self = [super initWithDictionary:dictionaryValue error:error];
if (self == nil) {
//DO SOMETHING WITH SELF AND RETURN A NON NIL OBJECT
return self;
}
return self;
}
My question is the following: if itemList is null, i.e., from the server null response comes for itemList, and then I want to override the default initWithDictionary behavior to DO SOMETHING AND RETURN A NON NIL OBJECT from the constructor of Item.h how do I do it? The code is not reaching this constructor to my surprise, because it was null when Menu.h was being formed.. I did specify the (NSValueTransformer) as well.. Any leads ? Thanks!
If
itemList
isnull
in the JSON, Mantle won't call your transformer, soItem
's initializer is never called.You can specify a default by changing the
Menu
model like this: