Ios Mantle - doing initWithDictionary correctly by default
I am facing the following problem.
I have class Menu.h and Item.h. The menu is similar to a restaurant menu and has multiple categories (like appetizers, salads, etc.), and each menu has multiple items. So Menu.h has an NSArray property called itemList. I am trying to automatically load these objects using the 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 a null response from the server comes for itemList and then I want to override the default initWithDictionary behavior to DO ANYTHING AND RETURN A NON-ILLEGAL OBJECT from the Item constructor. h how should i do this? The code doesn't get to that constructor to my surprise because it was null when Menu.h was being formed. I also specified (NSValueTransformer) .. Any leads? Thank!
source to share
If itemList
- null
in JSON, Mantle will not call your transformer, so the initializer is Item
never called.
You can provide a default by changing the model Menu
as follows:
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError *__autoreleasing *)error {
// Create itemListDefault value.
NSDictionary *defaults = @{
@"itemList" : itemListDefault
};
dictionaryValue = [defaults mtl_dictionaryByAddingEntriesFromDictionary:dictionaryValue];
return [super initWithDictionary:dictionaryValue error:error];
}
source to share