iOS CollectioniOS开发技术集合iOS-Swift

Swift Runtime分析:还像OC Runtime一样吗?

2016-04-20  本文已影响2032人  John_LS

转载原文地址

Swift是苹果2014年发布的编程开发语言,可与Objective-C共同运行于Mac OS和iOS平台,用于搭建基于苹果平台的应用程序。Swift已经开源,目前最新版本为2.2。我们知道Objective-C是具有动态性的,能够通过runtime API调用和替换任意方法,那Swift也具有这些动态性吗?

分析用例

我们拿一个纯Swift类和一个继承自NSObject的类的类来做分析,这两个类里包含尽量多的Swift的类型比如Character、String、AnyObject、Tuple。
代码如下:

class TestASwiftClass {
    var aBoll : Bool = true
    var aInt : Int = 0
    var aFloat : Float = 123.45
    var aDouble : Double = 1234.567
    var  aString :String = "abc"
    var aObject : AnyObject! = nil
    func testReturnVoidWithaId(aId : UIView) {
        print("TestASwiftClass.testReturnVoidWithaId")
    }
}

class testSwiftVC : UIViewController {
    var aBoll : Bool = true
    var aInt : Int = 0
    var aFloat : Float = 123.45
    var aDouble : Double = 1234.567
    var  aString :String = "abc"
    var aObject : AnyObject! = nil
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    }
    func testReturnVoidWithaId(aId : UIView) {
        print("testSwiftVC.testReturnVoidWithaId")
    }
    func testReturnVoidWithBool(aBool : Bool , aInteger : Int , aFloat : Float , aString : String , aObject : AnyObject) {
        print("testSwiftVC.testReturnVoidWithBool")
    }
    func testReturnTuple(aBool : Bool , aInteger : Int , aFloat : Float) -> (Bool , Int , Float){
        print("testSwiftVC.testReturnTuple")
        return (aBool,aInteger,aFloat)
    }
    func testReturnVoidWithCharacter(aCharacter : Character ) {
        print("testSwiftVC.testReturnVoidWithCharacter")
    }
    func tableView(table : UITableView , numberOfRowsInSection section : Int) -> Int {
        print("testSwiftVC.tableView(table : UITableView , numberOfRowsInSection section : Int) -> Int")
        return 20
    }
}
方法、属性

动态性比较重要的一点就是能够拿到某个类所有的方法、属性,我们使用如下代码来打印方法和属性列表。

func showClsRuntime (cls : AnyClass)  {
    print("start methodList")
    var  methodNum : UInt32 = 0
    let methodList = class_copyMethodList(cls, &methodNum)
    for index in 0..<numericCast(methodNum) {
        let method : Method = methodList[index]
        print(String(UTF8String: method_getTypeEncoding(method)))
        print(String(UTF8String: method_copyReturnType(method)))
        print(String(_sel: method_getName(method)))
    }
    free(methodList)
    print("end methodList")
    
    print("start propertyList")
    
    var propertyNum : UInt32 = 0
    let propertyList = class_copyPropertyList(cls, &propertyNum)
    for index in 0..<numericCast(propertyNum) {
        let property : objc_property_t = propertyList[index]
        print(String(UTF8String: property_getName(property)))
        print(String(UTF8String: property_getAttributes(property)))
    }
    free(propertyList)
    print("end propertyList")
    
}

调用showClsRuntime的代码如下:

let aSwiftClass : TestASwiftClass = TestASwiftClass()
        showClsRuntime(object_getClass(aSwiftClass))
        print("\n\n\n")
        showClsRuntime(object_getClass(self))

看看我们得到什么结果?

***start methodList
---end methodList


***start propertyList
---end propertyList




***start methodList
Optional("B16@0:8")
Optional("B")
aBoll
Optional("v20@0:8B16")
Optional("v")
setABoll:
Optional("q16@0:8")
Optional("q")
aInt
Optional("v24@0:8q16")
Optional("v")
setAInt:
Optional("f16@0:8")
Optional("f")
aFloat
Optional("v20@0:8f16")
Optional("v")
setAFloat:
Optional("d16@0:8")
Optional("d")
aDouble
Optional("v24@0:8d16")
Optional("v")
setADouble:
Optional("@16@0:8")
Optional("@")
aString
Optional("v24@0:8@16")
Optional("v")
setAString:
Optional("@16@0:8")
Optional("@")
aObject
Optional("v24@0:8@16")
Optional("v")
setAObject:
Optional("v24@0:8@16")
Optional("v")
testReturnVoidWithaId:
Optional("v48@0:8B16q20f28@32@40")
Optional("v")
testReturnVoidWithBool:aInteger:aFloat:aString:aObject:
Optional("q32@0:8@16q24")
Optional("q")
tableView:numberOfRowsInSection:
Optional("v16@0:8")
Optional("v")
didReceiveMemoryWarning
Optional("@32@0:8@16@24")
Optional("@")
initWithNibName:bundle:
Optional("v16@0:8")
Optional("v")
viewDidLoad
Optional("v20@0:8B16")
Optional("v")
viewDidAppear:
Optional("@?")
Optional("@?")
.cxx_destruct
Optional("@24@0:8@16")
Optional("@")
initWithCoder:
---end methodList


***start propertyList
Optional("aBoll")
Optional("TB,N,VaBoll")
Optional("aInt")
Optional("Tq,N,VaInt")
Optional("aFloat")
Optional("Tf,N,VaFloat")
Optional("aDouble")
Optional("Td,N,VaDouble")
Optional("aString")
Optional("T@\"NSString\",N,C,VaString")
Optional("aObject")
Optional("T@,N,&,VaObject")
---end propertyList

对于纯Swift的TestASwiftClass来说任何方法、属性都未获取到。

对于TestSwiftVC来说除testReturnTuple、testReturnVoidWithaCharacter两个方法外,其他的都获取成功了。

这是为什么?

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

但为什么testReturnTuple testReturnVoidWithaCharacter却又获取不到呢?

从Objective-c的runtime 特性可以知道,所有运行时方法都依赖TypeEncoding,也就是method_getTypeEncoding返回的结果,他指定了方法的参数类型以及在函数调用时参数入栈所要的内存空间,没有这个标识就无法动态的压入参数(比如testReturnVoidWithaId: Optional("v24@0:8@16") Optional("v"),表示此方法参数共需24个字节,返回值为void,第一个参数为id,第二个为selector,第三个为id),而Character和Tuple是Swift特有的,无法映射到OC的类型,更无法用OC的typeEncoding表示,也就没法通过runtime获取了。

Method Swizzling

动态性最常用的就是方法替换(Method Swizzling),将类的某个方法替换成自定义的方法,从而达到hook的作用。

  • 对于纯Swift类(如TestASwiftClass)来说,无法通过objc runtime替换方法,因为由上面的测试可知拿不到这些方法、属性

Method Swizzling的代码如下:

///Method Swizzeing runtime动态替换方法
func methodSwizze(cls : AnyClass,originalSelector : Selector , swizzeSelector : Selector)  {
    let originalMethod = class_getInstanceMethod(cls, originalSelector)
    let swizzeMethod = class_getInstanceMethod(cls, swizzeSelector)
    
    let didAddMethod = class_addMethod(cls, originalSelector, method_getImplementation(swizzeMethod), method_getTypeEncoding(swizzeMethod))
    
    if didAddMethod {
        class_replaceMethod(cls, swizzeSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
    }else {
        method_exchangeImplementations(originalMethod, swizzeMethod)
    }
    
}

我们替换两个可以被runtime获取到的方法:viewDidAppear和testReturnVoidWithaId

  override func viewDidLoad() {
        super.viewDidLoad()
//        let aSwiftClass : TestASwiftClass = TestASwiftClass()
//        showClsRuntime(object_getClass(aSwiftClass))
//        print("\n\n\n")
//        showClsRuntime(object_getClass(self))
        
        methodSwizze(object_getClass(self), originalSelector: Selector("viewDidAppear:"), swizzeSelector: Selector("sz_viewDidApper:"))
        methodSwizze(object_getClass(self), originalSelector: Selector("testReturnVoidWithaId:"), swizzeSelector: Selector("sz_testReturnVoidWithaId:"))
        testReturnVoidWithaId(self.view)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        print("F:\(__FUNCTION__) L:\(__LINE__))")
    }
    func testReturnVoidWithaId(aId : UIView) {
        print("testSwiftVC.testReturnVoidWithaId------F:\(__FUNCTION__) L:\(__LINE__))")
    }
    
    func sz_viewDidApper(animated : Bool) {
        super.viewDidAppear(animated)
        print("SZ------F:\(__FUNCTION__) L:\(__LINE__))")
        
    }
    
    func sz_testReturnVoidWithaId(aId : UIView) {
        print("SZ:testSwiftVC.testReturnVoidWithaId------F:\(__FUNCTION__) L:\(__LINE__))")
    }
    

打印的日志为:

testSwiftVC.testReturnVoidWithaId------F:testReturnVoidWithaId L:90)
SZ------F:sz_viewDidApper L:95)

说明viewDidAppear已经被替换,但是testReturnVoidWithaId却没有被替换,这是为何?

我们在方法里打个断点看看,如图:

屏幕快照 2016-04-20 下午3.13.31.png

可以看到区别,调用sz_viewDidAppear栈的前一帧为@objc TestSwiftVC.sz_viewDidAppear(Bool) -> ()有个@objc标识,而调用testReturnVoidWithaId则没有此标识。

@objc用来做什么的?与动态性有关吗?

@objc

找到官方文档读读。

可以知道@objc是用来将Swift的API导出给Objective-C和Objective-C runtime使用的,如果你的类继承自Objective-c的类(如NSObject)将会自动被编译器插入@objc标识。

我们在把TestASwiftClass(纯Swift类)的方法、属性前都加个@objc 试试,如:

class TestASwiftClass {
   @objc  var aBoll : Bool = true
   @objc var aInt : Int = 0
   @objc var aFloat : Float = 123.45
   @objc var aDouble : Double = 1234.567
   @objc var  aString :String = "abc"
   @objc var aObject : AnyObject! = nil
   @objc func testReturnVoidWithaId(aId : UIView) {
        print("TestASwiftClass.testReturnVoidWithaId")
    }
}

查看日志可以发现加了@objc的方法、属性均可以被runtime获取到了。

***start methodList
Optional("B16@0:8")
Optional("B")
aBoll
Optional("v20@0:8B16")
Optional("v")
setABoll:
Optional("q16@0:8")
Optional("q")
aInt
Optional("v24@0:8q16")
Optional("v")
setAInt:
Optional("f16@0:8")
Optional("f")
aFloat
Optional("v20@0:8f16")
Optional("v")
setAFloat:
Optional("d16@0:8")
Optional("d")
aDouble
Optional("v24@0:8d16")
Optional("v")
setADouble:
Optional("@16@0:8")
Optional("@")
aString
Optional("v24@0:8@16")
Optional("v")
setAString:
Optional("@16@0:8")
Optional("@")
aObject
Optional("v24@0:8@16")
Optional("v")
setAObject:
Optional("v24@0:8@16")
Optional("v")
testReturnVoidWithaId:
---end methodList
dynamic

文档里还有一句说明:

加了@objc标识的方法、属性无法保证都会被运行时调用,因为Swift会做静态优化。要想完全被动态调用,必须使用dynamic修饰。使用dynamic修饰将会隐式的加上@objc标识。

这也就解释了为什么testReturnVoidWithaId无法被替换,因为写在Swift里的代码直接被编译优化成静态调用了。

而viewDidAppear是继承Objective-C类获得的方法,本身就被修饰为dynamic,所以能被动态替换。

我们把TestSwiftVC方法前加上dynamic再测一把,如图:

屏幕快照 2016-04-20 下午3.19.25.png

从堆栈也可以看出,方法的调用前增加了@objc标识,testReturnVoidWithaId方法被替换成功了。

同样的做法,我们把TestASwiftClass的方法和属性也都加上dynamic修饰,做Method Swizzling,同样获得成功,如图

屏幕快照 2016-04-20 下午3.19.39.png
Objective-C获取Swift runtime信息

在Objective-c代码里使用objc_getClass("TestSwiftVC");会发现返回值为空,这是为什么?Swift代码中的TestSwiftVC类,在OC中还是这个名字吗?
我们初始化一个对象,并断点和打印看看,如下图:

屏幕快照 2016-04-20 下午3.21.44.png

可以看到Swift中的TestSwiftVC类在OC中的类名已经变成TestSwift.TestSwiftVC,即规则为SWIFT_MODULE_NAME.类名称,在普通源码项目里SWIFT_MODULE_NAME即为ProductName,在打好的Cocoa Touch Framework里为则为导出的包名。

所以要想从Objective-c中获取Swift类的runtime信息得这样写:

屏幕快照 2016-04-20 下午3.24.01.png
Objective-C替换Swift函数

给TestSwiftVC和TestASwiftClass的testReturnVoidWithaId函数加上dynamic修饰,然后我们在Objective-C代码里替换为testReturnVoidWithaIdImp函数:

![Upload 屏幕快照 2016-04-20 下午3.24.10.png failed. Please try again.]

运行之后我们得到结果

F:void testReturnVoidWithaIdImp(__strong id, SEL, __strong id) L:20 self=<TestSwift.TestSwiftVC: 0x7fb4e1d148f0>
F:void testReturnVoidWithaIdImp(__strong id, SEL, __strong id) L:20 self=TestSwift.TestASwiftClass

说明两者的方法在加上dynamic修饰后,均能在Objective-c里被替换。(TestSwiftVC的testReturnVoidWithaId不加dynamic也会打印日志,为什么?留给读者思考)

总结

  • 纯Swift类没有动态性,但在方法、属性前添加dynamic修饰可以获得动态性。
上一篇下一篇

猜你喜欢

热点阅读