How to set default value in iOS Mantle model subclass

旧城冷巷雨未停 提交于 2019-12-08 18:46:37

问题


@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.


回答1:


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];
}



回答2:


You can set the default value in init method.

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


来源:https://stackoverflow.com/questions/23064204/how-to-set-default-value-in-ios-mantle-model-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!