Several methods about iOS dictionary transfer model

Here I will introduce two kinds of dictionary to die

1:KVC 2:runTime dictionary model

Let us talk about the two kinds of different KVC is traversing the dictionary key values in the model class to go inside to find there is no corresponding key, whereas runtime is in the dictionary to find the traversal properties there is no corresponding key, in the actual development, because the background data returned more fields that can be used in relatively less so with high efficiency runtime.


KVC principle: key encoding is used to indirectly access the object properties of the mechanism, through the setValue:forKey and ValueForkey to access member variables, the amount of code is relatively simple to use.

Usage method:

1 to create a Model class, in which the.H declaration of the two methods, and the need to declare the properties (I can refer to the automatic declaration of attributes to complete this step)

– (instancetype) initWithDictionary: (NSDictionary *) dict;

(instancetype) provinceWithDictionary: (NSDictionary *) dict;

2 in the.M to achieve

– (instancetype) initWithDictionary: (NSDictionary *) Dict

{

If (self = [super init]) {

[self setValuesForKeysWithDictionary:dict];

}

Return self;

}

(instancetype) provinceWithDictionary: (NSDictionary *) Dict

{

Return [[self alloc] initWithDictionary:dict];

}

3 here we can directly adjust this method in ViewController

VisitorModel *model = [VisitorModel provinceWithDictionary:temDic]; completed the assignment of

Note: we are in the process of using KVC because it is through the dictionary to you in class to find a model without this property: or dictionary keyword: the program will throw an exception, here we have to play as a method:

– (void) setValue: (ID) value forUndefinedKey: (NSString *) key{

}

This is written on the right, if it is ID type, we declare a ID attribute, and then assign to it.

The use of KVC to introduce so much, it is also very convenient to use.


Second: runtime dictionary model

First talk about the model of a dictionary

Step 1, first create a model class, or through the automatic declaration of the attributes I encapsulate, and then paste the output into the.H

Step 2: call me this package on it, the principle of internal packaging as follows

1 create a category NSObject (model)

2, write a method in.H

(instancetype) modelWithDic: (NSDictionary*) dict; only need to pass a dictionary will automatically turn the model

3 in the.M method

(instancetype) modelWithDic: (NSDictionary*) dict{

1 create a class object

ID objc = [[self alloc]init]
;

2.// here need to wear a cout address, where cout is the total number of member attributes

Unsigned int count = 0;

3 this method is to copy the Model member variable attributes of the Ivar*, which is actually just a member of the array of variables (note the distinction between member attributes and attributes)

Ivar *ivarPlist =class_copyIvarList (self, & count);

4 traverse this number, then the value of count has become the number of your member variable attributes

For (int i=0; i< count++; i++) {

(1): get a member property name

Ivar ivar1 = ivarPlist[i];

(2): get the member name

NSString *propertyName = [NSString stringWithUTF8String: ivar_getName (ivar1)]

(3) access to the member property (the return value is C language, so the conversion)

NSString *propertyType = [NSString stringWithUTF8String: ivar_getTypeEncoding (ivar1)];

(4) to obtain the difference between the attributes and attributes of the key member

NSString *key = [propertyName substringFromIndex:1];

(5) to obtain Value

ID Value= dict[key];

(6) by KVC assignment (because if Value is empty, direct Crash, so here is a judge, if there is value to assign)

If (Value) {

[objc setValue:Value forKey:key]; / / value KVC replication cannot be empty

}

(7).Return objc;

}

This method is also relatively easy to understand, the above is only introduced a dictionary model, two is actually very simple

Two level model:

If we return data there is a dictionary, dictionary and a dictionary, we need to create a UserMode class, and then automatically generate the attribute, and then @class User; Model.h declared this property.

Continue to achieve the above for loop inside the code:

Determine whether the Value type is a dictionary, or that the attribute name does not contain NSDictionary

If ([Value isKindOfClass:[NSDictionary & &! [propertyType containsString:@ “NS”) {

1 convert property types to classes directly

Class modelClass =NSClassFromString (propertyType);

2 direct assignment

If (modelClass) {

Value = [modelClass modelWithDic:Value];

}

[Note: This is not enough, because the return value is not a class type conversion into User but @/ “user” Van Pham Van, so you want to implement string interception, concrete

PropertyType substringFromIndex:range.location +range.length]

Range =[propertyType rangeOfString:@ “/” “”;

PropertyType = [propertyType substringToIndex:range.location];

Class modelClass =NSClassFromString (propertyType);

}

Let us talk about the two kinds of different KVC is traversing the dictionary key values in the model class to go inside to find there is no corresponding key, whereas runtime is in the dictionary to find the traversal properties there is no corresponding key, in the actual development, because the background data returned more fields that can be used in relatively less so with high efficiency runtime.

id Value= dict[key];

(6).通过KVC进行赋值(因为Value如果为空,直接Crash,所以这里判断了一下,如果有值再去赋值)

if (Value) {

[objc setValue:Value forKey:key];//用kvc复制value不能为空

}

(7).return objc;

}

这个方法也是比较容易理解的,上面只是介绍了一级字典转模型,二级其实也非常简单

二级字典转模型:

假如我们返回数据里面有一个字典,字典里面还有一个字典,我们我们必须再创建一个UserMode类,然后自动生成属性,然后@class User;   再Model.h里面声明这个属性。

继续在上面的for循环里面实现一下代码:

判断Value类型是不是字典,或者属性名称不包含NSDictionary

if ([Value isKindOfClass:[NSDictionary class]] &&![propertyType containsString:@”NS”]) {

1.直接将属性类型转换成类

Class modelClass =NSClassFromString(propertyType);

2.直接给赋值

if (modelClass) {

Value =  [modelClass modelWithDic:Value];

}

[注意:这里是不行的,因为第类型转换成类返回值不是User  而是@/”user “/],所以你要进行字符串截取,具体

propertyType substringFromIndex:range.location +range.length]

range =[propertyType rangeOfString:@”/””];

propertyType = [propertyType substringToIndex:range.location];

Class modelClass =NSClassFromString(propertyType);

}