In the past when learning to parse data, we use a method is a life, and then added to the dictionary, and then copy, the trouble, but also can not guarantee a success, no error, I have encountered several key value problems!
You can actually replace the copy process with one sentence:
[Test setvaluesforkeyswithdictionary:dic];
Question one: What happens to the model that does not exist with the elements in dic?
At this time, the console output is empty "= (null)"
Question two: What happens if the dictionary does not exist with the elements in the model?
Error, or crash, because there is no corresponding age attribute in the model, causing the program to crash
Workaround: Implement a method: Setvalue:forundefinedkey:, this method can filter out the non-existent key value,
Specific operation:
Add in Model
Add the. h file:
-(void) SetValue: (ID) value Forundefinedkey: (NSString *) key;
And it needs to be implemented in the M file:
-(void) SetValue: (ID) value Forundefinedkey: (NSString *) key{ }
There is no need to write any content in the method!
Question three: If the key in DIC is different from the variable name in model, how should I assign a value?
As we can see from the previous, the key in DIC is assigned to the attribute with the same name as key in the model.
If the key value in DIC is the name in Username,model, the keyword, and so on, should change.
Solution: Start with the Setvalue:forundefinedkey method.
Change the values in DiC, and the properties of the model species,
Perfect the Setvalue:forundefinedkey method in model:
-(void) SetValue: (ID) value Forundefinedkey: (NSString *) key{ if([Key isequaltostring :@ "ID"]) { Self.age=value; } if ([Key isequaltostring:@ "username"]) { Self.name=value; } }
That's it! Of course, can also be directly in the DIC and model inside change into a consistent!
iOS Development-Dictionary quick Assignment