如何在iOS Mantle模型子类中设置默认值 [英] How to set default value in iOS Mantle model subclass
本文介绍了如何在iOS Mantle模型子类中设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@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
由于套样示例没有init方法,因此应在哪里初始化默认值的那些属性(searchTotalPagesAll,searchTotalPagesIdeas)?该模型具有需要此方法和其他一些属性的内部方法.
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.
推荐答案
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];
}
这篇关于如何在iOS Mantle模型子类中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文