Mapping from the dictionary to an object, which is provided by a method in KVC, this method is setvaluesforkeyswithdictionary:, very good, do not need you to one by one of the object to assign values and directly from the dictionary initialization can, but bad use will often crash, This tutorial will discuss the details of these uses.
First, initialize a dictionary first, as follows:
-------------------------------------------------------------------------------------
Nsdictionary *dic = [Nsdictionary Dictionarywithobjectsandkeys:
@ "y.x." @ "name",
@ "+" @ "age",
@ "Haidian District", @ "address", nil];
-------------------------------------------------------------------------------------
Create the Personinfomodel, as shown in the code below
-------------------------------------------------------------------------------------
#import <Foundation/Foundation.h>
@interface Personinfomodel:nsobject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *age;
@property (nonatomic, strong) NSString *address;
@end
-------------------------------------------------------------------------------------
#import "PersonInfoModel.h"
@implementation Personinfomodel
@end
-------------------------------------------------------------------------------------
After testing, print the following information:
The above is a very standard way to use it, and we'll add other to the property as shown in:
There is no error, it can be used normally, that is, when initializing an object in a dictionary, as long as the object contains these key values, it can be initialized normally, we then add a key value pair in the dictionary, as shown in:
Directly causes the program to crash because there is no sex attribute in the object, the workaround is to implement a method Setvalue:forundefinedkey: as shown in:
This will filter out to the non-existent key value assignment, if there is a property ID, and the ID itself is the system itself keyword, can not be used as a property, how to do?
Conclusion:
Setvalue:forundefinedkey: This method is the key, only after the existence of this method, you can filter out the non-existent key-value pairs and prevent crashes, at the same time, Setvalue:forundefinedkey: This method can also change the system's sensitive words, or, You manually map key values with different values, as you like.
Appendix:
Brother teaches you a way to deal with this problem of mapping to the wrong key value and causing the crash, first, you first inherit to the NSObject class, implementing the method Setvalue:forundefinedkey:
Then, you create a new model that inherits into the Yxmodel class, as shown in:
Then use, notice that it has a value of NULL, because there is no key value for this myid.
Workaround, overload the parent class with the Setvalue:forundefinedkey:, and then implement the following substitution.
KVC in Setvaluesforkeyswithdictionary