(Switch) example sentence model

  Reading books is not stealing stolen

  In iOS development, many times we need to use a dictionary to instantiate model, which means no need to instantiate a model when you have to repeat the write init method to instantiate the model, in order to "lazy", you can use macros to reduce code

  Define a header file "initWithDict.h"

1  // letters, numbers, _
 2  // ## macro definitions have connectors "\" indicating that the next line belong to the macro 
. 3  #define kInitH (name) \
 . 4 - ( ID ) initWithDict: (NSDictionary * ) dict ; \
 . 5 + ( ID ) ## WithDict name: (NSDictionary * ) dict;
 . 6  
. 7  #define kInitM (name) \
 . 8 + ( ID ) ## WithDict name: (NSDictionary * ) dict \
 . 9  {\
 10      return [[ the alloc Self] initWithDict: dict]; \
 . 11 }

  It is then introduced in each dictionary need to instantiate the model header file "initWithDict.h", used in the definition macro definition constructor directly, to pass the parameter name, for example:

#import "initWithDict.h"
@interface WKProvince : NSObject

@property (nonatomic, copy) NSString* name;
@property (nonatomic, strong) NSDictionary* cities;


kInitH(province);
 1 #import "WKProvince.h"
 2 
 3 @implementation WKProvince
 4 
 5 
 6 - (id)initWithDict:(NSDictionary *)dict
 7 {
 8     if (self = [super init]) {
 9         self.name = dict[@"name"];
10         self.cities = dict[@"cities"];
11     }
12     return  self;
13 }
14 
15 kInitM(province);
16 @end

 

Reproduced in: https: //www.cnblogs.com/pretty-guy/p/4060493.html

Guess you like

Origin blog.csdn.net/weixin_33971977/article/details/93199879