Brief introduction
OC was developed from the C language.
The reason why you can become a dynamic language is because of the runtime mechanism
Runtime is the OC in the runtime of some mechanisms;
The most important thing about OC Runtime is the messaging mechanism .
In the compilation phase, OC can call any function , immediately this function is not implemented , as long as the declaration will not error ;
And the C language calls the non-implemented function in the compilation phase to error;
Runtime role:
1. Send a message
1 The essence of the method invocation is to let the object send the message;
2.objc_msgsend, only objects can send messages;
3. Using the message mechanism premise, you must import the #import<objc/message.h>;
- The essence of a method invocation is to have the object send a message.
- Objc_msgsend, only objects can send messages, so start with OBJC.
- Use
消息机制 premise, must import #import <objc/message.h>
- Message mechanism simple to use
// 创建person对象 Person *p = [[Person alloc] init]; // 调用对象方法 [p eat]; // 本质:让对象发送消息 objc_msgSend(p, @selector(eat)); // 调用类方法的方式:两种 // 第一种通过类名调用 [Person eat]; // 第二种通过类对象调用 [[Person class] eat]; // 用类名调用类方法,底层会自动把类名转换成类对象调用 // 本质:让类对象发送消息 objc_msgSend([Person class], @selector(eat));
2 Exchange Method:
- Development of the use of the scene: The system's own method is not enough, to the system's own method to extend some functions, and maintain the original function.
- Method One: Inherit the class of the system, overriding the method.
- Mode two: Use runtime, Exchange method.
@implementation viewcontroller-(void) viewdidload {[Super viewdidload]; Additional setup after loading the view, typically from a nib. Requirements: To provide functionality to the Imagenamed method, each time the picture is loaded to determine whether the tablet is loaded successfully. Step one: First make a classification, define a can load the picture and can print method + (Instancetype) Imagewithname: (NSString *) name; Step two: Exchange imagenamed and Imagewithname implementation, you can call Imagewithname, indirectly invoke the implementation of Imagewithname. UIImage *image = [UIImage imagenamed:@ "123"];} @end @implementation UIImage (Image)//load classification to memory when Call + (void) load{//Exchange method//Get Imagewithname method address methods Imagewithna me = Class_getclassmethod (self, @selector (imagewithname:)); Get Imagewithname method Address ImageName = Class_getclassmethod (self, @selector (imagenamed:)); Interchange method address, equivalent to interchange implementation mode Method_exchangeimplementations (Imagewithname, imageName);} The system method imagenamed cannot be overridden in the classification, because the function of the system will be overwritten, and the classification cannot be called super.//can both load the picture and print + (Instancetype) Imagewithname: (NSString *) name {//Call imagewithname here, equivalent to calling imagename UIImage *image = [self imagewithname:name]; if (image = = nil) { NSLog (@ "Load empty picture"); } return image; @end
3. Dynamic Add method
- Development Use Scenario: If a class method is very many, load the class to memory is also more expensive, need to give each method to generate a mapping table, you can use the dynamic to a class, add methods to solve.
- Classic Interview questions: There is no use of performselector, in fact, I would like to ask you have not dynamically added methods.
- Simple to use
@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. Person *p = [[Person alloc] init]; // 默认person,没有实现eat方法,可以通过performSelector调用,但是会报错。 // 动态添加方法就不会报错 [p performSelector:@selector(eat)];}@end@implementation Person// void(*)()// 默认方法都有两个隐式参数,void eat(id self,SEL sel){ NSLog(@"%@ %@",self,NSStringFromSelector(sel));}// 当一个对象调用未实现的方法,会调用这个方法处理,并且会把对应的方法列表传过来.// 刚好可以用来判断,未实现的方法是不是我们想要动态添加的方法+ (BOOL)resolveInstanceMethod:(SEL)sel{ if (sel == @selector(eat)) { // 动态添加eat方法 // 第一个参数:给哪个类添加方法 // 第二个参数:添加方法的方法编号 // 第三个参数:添加方法的函数实现(函数地址) // 第四个参数:函数的类型,(返回值+参数类型) v:void @:对象->self :表示SEL->_cmd class_addMethod(self, @selector(eat), eat, "[email protected]:"); } return [super resolveInstanceMethod:sel];}@end
4. Adding attributes to a category
- Principle: To declare a property to a class, the essence is to add an association to the class, not directly add the value of the memory space to the class storage space.
@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // 给系统NSObject类动态添加属性name NSObject *objc = [[NSObject alloc] init]; objc.name = @"fa哥"; NSLog(@"%@",objc.name);}@end// 定义关联的keystatic const char *key = "name";@implementation NSObject (Property)- (NSString *)name{ // 根据关联的key,获取关联的值。 return objc_getAssociatedObject(self, key);}- (void)setName:(NSString *)name{ // 第一个参数:给哪个对象添加关联 // 第二个参数:关联的key,通过这个key获取 // 第三个参数:关联的value // 第四个参数:关联的策略 objc_setAssociatedObject(self, key, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}@end
5. Dictionary Turn model
- Design Model: The first step of a dictionary-to-model
- Model properties, usually corresponding to key one by one in the dictionary
- Problem: One of the generation model properties, very slow?
- Requirements: Can be automatically based on a dictionary to generate the corresponding properties.
- WORKAROUND: Provide a classification that generates a corresponding property string specifically based on the dictionary.
@implementation NSObject (LOG)//Auto Print attribute string + (void) Resolvedict: (nsdictionary *) dict{//Stitching property String Code nsmutablestring *STRM = [nsmutablestring string]; 1. Iterate through the dictionary and remove all keys from the dictionary to generate the corresponding property code [dict enumeratekeysandobjectsusingblock:^ (ID _nonnull key, id _nonnull obj, BOOL * _nonnull stop) {//type often changed, pumped out nsstring *type; if ([obj iskindofclass:nsclassfromstring (@ "__nscfstring")]) {type = @ "NSString"; }else if ([obj iskindofclass:nsclassfromstring (@ "__nscfarray")]) {type = @ "Nsarray"; }else if ([obj iskindofclass:nsclassfromstring (@ "__nscfnumber")]) {type = @ "int"; }else if ([obj iskindofclass:nsclassfromstring (@ "__nscfdictionary")]) {type = @ "Nsdictionary"; }//property string NSString *str; if ([Type containsstring:@ "NS"]) {str = [NSString stringwithformat:@ "@property (nonatomic, strong)%@ *%@;", Ty Pe,key]; }else{str = [NSString Stringwithformat:@ "@property (nonatomic, assign)%@%@;", Type,key]; }//Each generated property string, it wraps itself. [StrM appendformat:@ "\n%@\n", str]; }]; It would be nice to print out the stitched strings. NSLog (@ "%@", StrM);} @end
- How to turn a dictionary into a model one: KVC
@implementation Status+ (instancetype)statusWithDict:(NSDictionary *)dict{ Status *status = [[self alloc] init]; [status setValuesForKeysWithDictionary:dict]; return status;}@end
- KVC dictionary to model cons: You must ensure that the properties in the model correspond to key one by one in the dictionary.
- If they are not consistent, they will invoke
[<Status 0x7fa74b545d60> setValue:forUndefinedKey:] errors that the report cannot key find.
- Analysis: The property in the model and the key of the dictionary do not correspond, the system will call an
setValue:forUndefinedKey: error.
- Solution: Rewrite the object
setValue:forUndefinedKey: , the system method to cover, you can continue to use KVC, dictionary to model.
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{}
- How to Model A dictionary two: Runtime
- Idea: Use the runtime, traverse all the properties of the model, according to the model's property name, go to the dictionary to find the key, take out the corresponding value, to the model's properties assigned value.
- Step: Provide a nsobject classification, a special dictionary to the model, all the models can be transferred through this classification.
@implementation viewcontroller-(void) viewdidload {[Super viewdidload]; Additional setup after loading the view, typically from a nib. Parse plist file NSString *filepath = [[NSBundle mainbundle] pathforresource:@ "status.plist" oftype:nil]; Nsdictionary *statusdict = [Nsdictionary Dictionarywithcontentsoffile:filepath]; Gets the dictionary array nsarray *dictarr = statusdict[@ "statuses"]; Automatically generate a property string for the model//[NSObject resolvedict:dictarr[0][@ "user"]; _statuses = [Nsmutablearray array]; Iterates through the dictionary array for (nsdictionary *dict in Dictarr) {Status *status = [status Modelwithdict:dict]; [_statuses Addobject:status]; }//test data NSLog (@ "%@%@", _statuses,[_statuses[0] user]);} @end @implementation NSObject (model) + (Instancetype) modelwithdict: (nsdictionary *) dict{//idea: Traverse all properties in the model-"Use runtime//0. Create the corresponding object id OBJC = [[Self alloc] init]; 1. Use runtime to assign values to member properties in an object//class_copyivarlist: Gets all the member properties in the class//Ivar: The meaning of the member property///The first parameter: Represents the Get member property in which class//second parameter: Indicates how many member properties of this class, passing in an int variable address, will automatically assign a value to the variable//return value Ivar *: Refers to a Ivar array, will put all the member properties in an array, through the returned array can be fully obtained. /* Similar to the following wording Ivar Ivar; Ivar ivar1; Ivar ivar2; Defines an array of Ivar a Ivar a[] = {IVAR,IVAR1,IVAR2}; Point to the first element of the array with a Ivar * pointer Ivar *ivarlist = A; Access the first element of the array according to the pointer ivarlist[0]; */unsigned int count; Gets all member properties in the class Ivar *ivarlist = Class_copyivarlist (self, &count); for (int i = 0; i < count; i++) {///according to the angle label, remove the corresponding member property from the array Ivar Ivar = Ivarlist[i]; Gets the member property name NSString *name = [NSString stringwithutf8string:ivar_getname (Ivar)]; Handle key in the dictionary of member properties--//starting from the first corner to intercept nsstring *key = [name substringfromindex:1]; Find the corresponding value ID in the dictionary according to the member property name value = Dict[key]; Secondary conversions: If there is a dictionary in the dictionary, you also need to convert the corresponding dictionary into a model//To determine if value is a dictionary if ([Value Iskindofclass:[nsdictionary class]]) { Dictionary to model//Get model class object, call Modelwithdict//model class name is known, is the type of member property// Gets the member property type NSString *type = [NSString stringwithutf8string:ivar_gettypeencoding (Ivar)]; Generated is this @ "@\" user\ "type-" @ "User" in the OC string \ "-", \ is escaped meaning, does not occupy the character//clipping type string Nsrange range = [ty PE rangeofstring:@ "\" "]; Type = [Type SubstringFromIndex:range.location + range.length]; Range = [Type rangeofstring:@ "\"]; Clip to which corner label, not including the current corner label type = [Type substringToIndex:range.location]; Generates a class object based on the string class name class Modelclass = nsclassfromstring (type); if (Modelclass) {//have corresponding model only need to go//Turn dictionary to model value = [Modelclass modelwithdict:value]; }}//Three-level conversion: Nsarray is also a dictionary that converts the dictionary in an array into a model. Determine if the value is an array if ([Value Iskindofclass:[nsarray class]]) {//To determine if the corresponding class has implemented a dictionary array to the model array of the protocol if ([self Respondstoselector: @selector (arraycontainmodelclass)]) {//Convert to ID type, you can invoke the method ID of any object idself = Self Gets the model corresponding to the dictionary in the array nsstring *type = [Idself Arraycontainmodelclass][key]; Generate model Class Classmodel = nsclassfromstring (type); Nsmutablearray *ARRM = [Nsmutablearray array]; Iterate through the dictionary array, generate the model array for (Nsdictionary *dict in value) {//dictionary to model ID models = [Classmodel modelwithdict:dict]; [Arrm Addobject:model]; }//Assign the model array to value value = ARRM; }} if (value) {//has values, you need to assign values to the model's properties//use KVC to assign values to the properties in the model [OBJC Setvalue:value Forkey:key]; }} return OBJC;} @end
iOS runtime