Swift Runtime分析与OC Runtime区别

1.我们知道Objective-C是一门动态性语言,能够通过runtime API调用和替换任意方法,那Swift也具有这些动态性吗?

  • 分析示例

PureSwiftClass是纯Swift类,MuixSwiftClass是一个继承自NSObject的类。两个类中都包含了属性、方法。

//MARK: - 纯SwiftClass
class PureSwiftClass {
    @objc var bolValue: Bool = false
    @objc var age: Int = 0
    @objc var height: Float = 0
    @objc var name: String?
    @objc var exName: String?
    @objc func testPureAction() {
        print("PureSwiftClass.testPureAction")
    }
}


class MuixSwiftClass: UIViewController {

    @objc var bolValue: Bool = false
    @objc var age: Int = 0
    @objc var height: Float = 0
    @objc var name: String?
    @objc var exName: String?
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    @objc func createSubView(view : UIView) {
        print("MuixSwiftClass.createSubView")
    }
    
    @objc func testVoidWithBool(boolValue : Bool , tempInt : Int , tempFloat : Float , str : String , obj : AnyObject) {
        print("MuixSwiftClass.testVoidWithBool")
    }
    
//    @objc func testVoidWithTuple(boolValue : Bool , tempInt : Int , tempFloat : Float) -> (Bool , Int , Float){
//        print("MuixSwiftClass.testVoidWithTuple")
//        return (boolValue,tempInt,tempFloat)
//    }
//
//    @objc func testVoidWithCharacter(char : Character ) {
//        print("MuixSwiftClass.testVoidWithCharacter")
//    }

}
  • 动态获取方法、属性的方法
func showClsRuntime (cls: AnyClass)  {
        print("----------方法列表开始-----------")
        var  methodNum: UInt32 = 0
        let methodList: UnsafeMutablePointer! = class_copyMethodList(cls, &methodNum)
        for index in 0..! = class_copyPropertyList(cls, &propertyNum)
        for index in 0..
  • 方法调用示例
showClsRuntime(cls: MuixSwiftClass.self)
showClsRuntime(cls: PureSwiftClass.self)

  • 打印结果
MuixSwiftClass动态获取方法、属性
----------方法列表开始-----------
bolValue
setBolValue:
exName
setExName:
createSubViewWithView:
testVoidWithBoolWithBoolValue:tempInt:tempFloat:str:obj:
.cxx_destruct
name
setName:
initWithCoder:
initWithNibName:bundle:
viewDidLoad
viewDidAppear:
height
setHeight:
setAge:
age
----------方法列表结束-----------
----------属性列表开始-----------
bolValue
age
height
name
exName
----------属性列表结束-----------

PureSwiftClass动态获取方法、属性
----------方法列表开始-----------
bolValue
setBolValue:
exName
setExName:
testPureActionWithAId:
name
setName:
height
setHeight:
setAge:
age
----------方法列表结束-----------
----------属性列表开始-----------
bolValue
age
height
name
exName
----------属性列表结束-----------

纯Swfit类PureSwiftClass都未获取到方法、属性,对于MuixSwiftClass获取成功。

1.纯Swift类的函数调用已经不再是Objective-c的运行时发消息,而是类似C++的vtable,在编译时就确定了调用哪个函数,所以没法通过runtime获取方法、属性。

2.MuixSwiftClass继承自UIViewController,基类NSObject,而Swift为了兼容Objective-C,凡是继承自NSObject的类都会保留其动态性,所以我们能通过runtime拿到他的方法。这里有一点说明:老版本的Swift(如2.2)是编译期隐式的自动帮你加上了@objc,而4.0以后版本的Swift编译期去掉了隐式特性,必须使用显式标示!

3.可以看到MuixSwiftClass中有两个注释掉的方法。因为此两个方法在加上@objc后,Xcode直接报错提示此方法参数类型不能映射到OC类型,runtime也就无法获取。

4.因为方法参数里的Character和Tuple两个类型是Swift独有的,无法映射到OC的类型。

5.结合以上几点,不管是纯Swift类还是继承自NSObject的类只要在属性和方法前面添加@objc关键字就可以使用runtime。

Method Swizzling

MuixSwiftClass方法替换代码

extension MuixSwiftClass {
  @objc func swizzle_viewWillAppear(_ animated: Bool) {
        swizzle_viewWillAppear(animated)
        print("swizzle_viewWillAppear")
    }
}


extension MuixSwiftClass: SelfAware{
    static func awake() {
        takeOnceTime
    }
    private static let takeOnceTime: Void = {
        let originalSelector = #selector(viewWillAppear(_:))
        let swizzledSelector = #selector(swizzle_viewWillAppear(_:))
        swizzlingForClass(MuixSwiftClass.self, originalSelector: originalSelector, swizzledSelector: swizzledSelector)
    }()
}

PureSwiftClass方法替换代码

extension PureSwiftClass {
    @objc func swizzle_testPureAction() {
        swizzle_testPureAction()
        print("swizzle_testPureAction")
    }
}

extension PureSwiftClass: SelfAware {
    static func awake() {
        self.takeOnceTime
    }
    
    private static let takeOnceTime: Void = {
        let originalSelector = #selector(testPureAction)
        let swizzledSelector = #selector(swizzle_testPureAction)
        swizzlingForClass(OtherPureSwiftClass.self, originalSelector: originalSelector, swizzledSelector: swizzledSelector)
    }()
}

方法调用代码(具体调用原理可参考 资源链接)

protocol SelfAware: class {
    static func awake()
    static func swizzlingForClass(_ forClass: AnyClass, originalSelector: Selector, swizzledSelector: Selector)
}

extension SelfAware {
    
    static func swizzlingForClass(_ forClass: AnyClass, originalSelector: Selector, swizzledSelector: Selector) {
        let originalMethod = class_getInstanceMethod(forClass, originalSelector)
        let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector)
        guard (originalMethod != nil && swizzledMethod != nil) else {
            return
        }
        if class_addMethod(forClass, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) {
            class_replaceMethod(forClass, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
        } else {
             method_exchangeImplementations(originalMethod!, swizzledMethod!)
        }
    }
}

class NothingToSeeHere {
    static func harmlessFunction() {
        let typeCount = Int(objc_getClassList(nil, 0))
        let types = UnsafeMutablePointer.allocate(capacity: typeCount)
        let autoreleasingTypes = AutoreleasingUnsafeMutablePointer(types)
        objc_getClassList(autoreleasingTypes, Int32(typeCount))
        for index in 0 ..< typeCount {
            (types[index] as? SelfAware.Type)?.awake()
        }
        types.deallocate()
    }
}

extension UIApplication {
    private static let runOnce: Void = {
        NothingToSeeHere.harmlessFunction()
    }()
    override open var next: UIResponder? {
        UIApplication.runOnce
        return super.next
    }
}

打印如下

swizzle_viewWillAppear
PureSwiftClass.testPureAction

说明Swfit中只能替换系统方法,而自定义的方法之间无法进行替换

示例代码 项目链接

你可能感兴趣的:(Swift Runtime分析与OC Runtime区别)