zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

iOS: Runtime实战

ios 实战 runtime
2023-09-14 09:04:14 时间

返回上级目录:iOS面试专题一


在这里插入图片描述

1.[obj foo]和objc_msgSend()函数之间有什么关系?

[obj foo]在编译后(编译器的处理过程之后)就变成了objc_msgSend(obj,selector(foo),参数…),然后开始runtime的消息传递过程

2.runtime如何通过selector找到对应的IMP地址的?

当前类的缓存–>当前类方法列表–>父类缓存–>父类方法列表–>根类缓存–>根类方法列表–>消息转发流程

3.能否向编译后的类中增加实例变量?

不能,class_ro_t,readonly,所以编译后不可修改,但是可以向动态添加的类中增加实例变量,只要在添加注册类对方法前添加实例变量就可以

4.runtime在项目中的实际使用

4.1 数组越界不崩溃 method swizzling(objectAtIndex)

请添加图片描述
请添加图片描述

runtime介绍以及在项目中的实际运用

  • swizzlingMethod的实现
BOOL swizzlingMethod(Class aClass, SEL originalSelector, SEL swizzlingSelector) {
    Method originMethod = class_getInstanceMethod(aClass, originalSelector);
    Method swizzlingMathod = class_getInstanceMethod(aClass, swizzlingSelector);
    BOOL didAddMethod = class_addMethod(aClass, originalSelector, method_getImplementation(swizzlingMathod), method_getTypeEncoding(swizzlingMathod));
    if (didAddMethod) {
        class_replaceMethod(aClass, swizzlingSelector, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
    }else{
        method_exchangeImplementations(originMethod, swizzlingMathod);
    }

4.2 字典转模型YYModel的内部实现

4.3 大量调用某个方法时直接调用IMP

Messaging(runtime) - apple developer

4.4 textView的_placeholderLabel

iOS swift UItextField UITextView占位文字

4.5 tableView索引栏的字体大小

tableView的子视图:UITableViewIndex
iOS runtime 动态拦截方法,设置参数 tableView改变索引栏的字体大小和颜色

4.6 对页面的进出添加一些统计日志信息 method swizzling

iOS:runtime 消息转发 Method_Swizzling 动态添加方法 动态方法解析

4.7 NSClassFromString,NSSelectorFromString,performSelector进行解耦

NSClassFromString,NSSelectorFromString…

iOS 组件通信方案
请添加图片描述