zoukankan      html  css  js  c++  java
  • iOS开发——model类模板(过滤null和ID)

       

        说明:model类模板已默认过滤null值,附加特殊情况的关键字ID名的冲突(需手动去掉注释代码)。MyMessageModel为示例的名字。可以自己随便起。

    1.自己创建一个继承与NSObject的类,用于当model数据模型用。然后在.h文件中根据接口文档或者json返回数据的添加相应属性。

       并复制以下model类模板代码.h文件的- (instancetype)initWithDictionary:(NSDictionary *)dictionary;方法到自己创建的数据模型类.h中。

    2.在自己的数据模型类.m文件中,复制以下model模板类.m中代码到自己创建的类.m中。

    model类.h文件

     1 #import <Foundation/Foundation.h>
     2 
     3 @interface MyMessageModel : NSObject
     4 
     5 
     6 // 示例属性名,根据后台接口返回的数据自己copy到此处
     7 
     8 @property (nonatomic, strong) NSString *namet;    
     9 
    10 /**
    11  *  Init the model with dictionary
    12  *
    13  *  @param dictionary dictionary
    14  *
    15  *  @return model
    16  */
    17 - (instancetype)initWithDictionary:(NSDictionary *)dictionary;
    18 
    19 @end

    modell类.m文件

     1 #import "MyMessageModel.h"
     2 
     3 @implementation MyMessageModel
     4 
     5 - (void)setValue:(id)value forUndefinedKey:(NSString *)key {
     6     
     7     /*  [Example] change property id to productID
     8      *
     9      *  if([key isEqualToString:@"id"]) {
    10      *
    11      *      self.productID = value;
    12      *      return;
    13      *  }
    14      */
    15     
    16     // show undefined key
    17 //    NSLog(@"%@.h have undefined key '%@', the key's type is '%@'.", NSStringFromClass([self class]), key, [value class]);
    18 }
    19 
    20 - (void)setValue:(id)value forKey:(NSString *)key {
    21     
    22     // ignore null value
    23     if ([value isKindOfClass:[NSNull class]]) {
    24         
    25         return;
    26     }
    27 
    28     [super setValue:value forKey:key];
    29 }
    30 
    31 - (instancetype)initWithDictionary:(NSDictionary *)dictionary {
    32     
    33     if ([dictionary isKindOfClass:[NSDictionary class]]) {
    34         
    35         if (self = [super init]) {
    36             
    37             [self setValuesForKeysWithDictionary:dictionary];
    38         }
    39     }
    40     
    41     return self;
    42 }
    43 
    44 @end

    3.对于极少情况下遇到的接口返回json数据带ID的参数和系统ID关键字冲突的解决。

      打开.m中

    /* [Example] change property id to productID 

    if([key isEqualToString:@"id"])

    self.productID = value;

    return; 

    */   打开这行的注释。将.h中冲突的ID属性名改成productID

    4.如何使用model类?     控制器导入模型头文件.h。 在网络请求回来的数据方法中,这样调用  

     MyMessageModel *model = [[MyMessageModel alloc] initWithDictionary:data];

    这样既可创建了一个数据模型。

  • 相关阅读:
    element ui 表单清空
    element ui 覆盖样式 方法
    element ui 修改表单值 提交无效
    element ui 抽屉里的表单输入框无法修改值
    element ui 抽屉首次显示 闪烁
    css 左侧高度 跟随右侧内容高度 自适应
    PICNUF框架
    elementui 抽屉组件标题 出现黑色边框
    vue 子组件跨多层调用父组件中方法
    vue 编辑table 数据 未点击提交,table里的数据就发生了改变(深拷贝处理)
  • 原文地址:https://www.cnblogs.com/LiuChengLi/p/5307605.html
Copyright © 2011-2022 走看看