1. The benefits of replacing dictionaries with models
? Disadvantages of using dictionaries
? In general, setting data and fetching data use "String type Key", when writing these keys, the compiler will not have any friendly prompts, need to knock
dict[@ "name"] =@ "Jack";
nsstring*name = dict[@ "name"];
Hand knocking string Key,key easy to write wrong? If the key is incorrectly written, the compiler will not have any warnings or errors, resulting in incorrect data or incorrect data.?? Benefits of using modelsThe so-called model, in fact, is the data model, specifically used to hold the data object, it is used to represent the data will be more professionalThe model sets the data and takes out the data through its properties, the property name if the error is written, the compiler will immediately error, so that the correctness of the data? When using a model to access properties, the compiler provides a series of hints to improve coding efficiency
App.name = @ "Jack";
nsstring*name = app.name;
2. Dictionary Turn Model
The process of dictionary-to-model is best encapsulated inside the model?? The model should provide a construction method that can pass in a dictionary parameter?-(instancetype) initwithdict: (nsdictionary*) dict;? + (instancetype) xxxwithdict: (nsdictionary*) dict;
3.instancetype
? instancetype on a type representation, as with an ID , can represent any object type?? Instancetype can only be used on return value types and cannot be used as an ID on parameter types?? One benefit of instancetype than ID : The compiler detects the true type of instancetype
4. The process of dictionary-to-model
5.Sample
#import <Foundation/Foundation.h> @interface mjapp:nsobject-(nsstring*) getname;-(nsstring*) geticon;-( Instancetype) Initwithdict: (Nsdictionary *) dict;+ (instancetype) appwithdict: (Nsdictionary *) dict; @end #import " MJApp.h "@interface Mjapp () @property (nonatomic,copy) nsstring *name; @property (nonatomic,copy) nsstring *icon; @end @implementation mjapp-(nsstring*) getname{ return self.name;} -(nsstring*) geticon{ return Self.icon;} -(Instancetype) Initwithdict: (nsdictionary *) dict{ if (self = [super init]) { self.name = dict[@ "name"]; Self.icon = dict[@ "icon"]; } return self;} + (Instancetype) appwithdict: (nsdictionary *) dict{ return [[Self alloc] initwithdict:dict];} @end
Dictionary and model of 6.ios