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

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

  • 相关阅读:
    数据挖掘实践(23):实战-- 建筑能源得分预测报告(一)
    返回闭包
    函数指针
    Rust 中的 Closure
    Moves, copies and clones in Rust
    Rust的闭包类型(Fn, FnMut, FnOne的区别)
    Clone VS Copy
    rust socket
    A simple UNIX socket listener in Rust
    【firecracker】系统启动与epoll事件循环
  • 原文地址:https://www.cnblogs.com/LiuChengLi/p/5307605.html
Copyright © 2020-2023  润新知