How to set the default value in a subclass of the Mantle iOS model

@interface Entity () @property (assign) int searchTotalPagesAll; @property (assign) int searchTotalPagesIdeas; @end @implementation Entity + (NSDictionary *)JSONKeyPathsByPropertyKey { return @{ @"Id": @"entity.id_entity", @"name": @"entity.name", @"coverage" : @"entity.coverage", @"id_city": @"entity.Id_City", @"cityName":@"entity.city", @"countryName":@"entity.country", @"stateName":@"entity.district", @"countryCode": @"entity.countrycode", @"keyword1": @"entity.key1", ... etc 

Since mantle examples do not have an init method, where should I initialize these properties (searchTotalPagesAll, searchTotalPagesIdeas) for default values? This model has internal methods that need this and a number of other properties.

+6
source share
2 answers

Whether you create a Mantle model in JSON or otherwise, the model is initialized using [-initWithDictionary:error:] . In your model class, you can add your default values ​​to the values ​​used to initialize the model:

 - (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError *__autoreleasing *)error { NSDictionary *defaults = @{ @"searchTotalPagesAll" : @(10), @"searchTotalPagesIdeas" : @(5) }; dictionaryValue = [defaults mtl_dictionaryByAddingEntriesFromDictionary:dictionaryValue]; return [super initWithDictionary:dictionaryValue error:error]; } 
+12
source

You can set the default value in the init method.

 - (instancetype)init { self = [super init]; if (self) { self.searchTotalPagesAll = 1; self.searchTotalPagesIdeas = 2; } return self; } 
+7
source

All Articles