Background
In client programming. Dictionary-to-model is a very common problem, Apple provides KVC to achieve nsdictionary to model injection, but KVC only can be single-layer shallow injection. And can not handle type conversion, key and attribute name is not correct, deep injection and other issues, the author from Masonry, developed a chain configuration injector to achieve depth injection, type conversion, key-property name mapping functions such as the lightweight injection framework SUPERKVC. Now it's open source to GitHub, click here to go. Welcome to star and Fork. Welcome to the frame with me intact!
This article will introduce SUPERKVC from two angles of application and principle.
How to use
The framework is similar to masonry, requiring the user to configure the injector parameters in a block of relevant method parameters, such as configuring the class to be created and injected, the type converter, the name Mapping, and so on, and the method returns the injected result. Assuming that the root element of the JSON is a dictionary, a model instance is returned. Assuming that the root element of the JSON is an array, it returns a list of models.
Shallow Injection Demo sample
Suppose we have JSON like the following. To be injected into the usermodel.
{ "id100075, "name"Greedy", "birthday"1993-03-06", "isViptrue, "partners[100236, 100244, 100083]}
@interface usermodel : nsobject @property(nonatomic,Assign) int64_t UserId;@property(nonatomic, copy)NSString*name;@property(nonatomic,Strong)NSDate*birthday;@property(nonatomic,Assign)BOOLISVIP;@property(nonatomic,Strong)Nsarray*partners;@end
Notice here a few "pit points", responding to the id corresponding is the model userId . The type of response is birthday NSString , and the model is of birthday type NSDate . The code that is injected with SUPERKVC is as follows.
//ResponseObject is A jsonobject (nsdictionary). Usermodel *usermodel = [Responseobject sk_injectwithinjector:^ (Superkvcinjector *injector) {//Configure the Model instance type to be generated and injected injector.bind ([Usermodel class ]); //configure key to attribute name Mapping injector.mapping (@ "id" ). to (@ "UserId" ); //Configuration type conversion Injector.format (@ "Birthday" ). with . Converter (^nsdate* (NSString *birthdaystring) { iOS JSON-to-model chained programming framework SUPERKVC using methods and principles