7
@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 doesn't have a init method, where should I initialize those properties (searchTotalPagesAll, searchTotalPagesIdeas) for default values ? This model has internal methods that need this and several other properties.

David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132
omarojo
  • 1,197
  • 1
  • 13
  • 26

2 Answers2

13

Whether you create a Mantle model from JSON or otherwise, the model is initialised with [-initWithDictionary:error:]. In your model class, you can add your defaults to the values used to initialise 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];
}
David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132
  • If I initialize in this way: [[MyMantleModelClass alloc] init] it won't trigger [-initWithDictionary:error:]. How can I force the former initializer to call the latter without they calling each other? thx. – Golden Thumb Feb 07 '15 at 14:23
  • 1
    If you aren't using `initWithDictionary` then you can just set the property values in `init`. – David Snabel-Caunt Feb 07 '15 at 18:02
9

You can set the default value in init method.

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.searchTotalPagesAll = 1;
        self.searchTotalPagesIdeas = 2;
    }
    return self;
}
Hilen
  • 761
  • 7
  • 8