先来看一段代码
class LTTech{
var age: Int=10
func tech(){
print("***tech***")
}
@objc var gender: Int = 1
@objc func findTech(){
print("***findTech***")
}
}
let t = LTTech()
func test(){
var methodCount: UInt32=0
let methodList = class_copyMethodList(LTTech.self, &methodCount)
for i in 0 ..< numericCast(methodCount) {
if let method = methodList?[i]{
let methodName = method_getName(method)
print("方法列表:\(String(describing: methodName))")
}else{
print("not found method")
}
}
var count: UInt32=0
let propertyList = class_copyPropertyList(LTTech.self, &count)
for i in 0 ..< numericCast(count) {
if let property = propertyList?[i] {
let propertyName = property_getName(property)
print("属性成员属性:\(String(describing: propertyName))")
}else{
print("not found property")
}
}
}
test()

//将上面代码中LTTech,替换为如下代码
class LTTech: NSObject {
var age: Int=10
func tech(){
print("***tech***")
}
}

通过run代码,发现没有输出任何内容,所以对于原生的Swift来说,是没有runtime特性的
结论:
1、对于纯Swift类来说,方法和属性不加任何修饰符的情况下。这个时候其实已经不具备所谓的Runtime特性
2、对于纯Swift类,方法和属性添加@objc标识的情况下,当前可以通过Runtime API拿到,但是在OC中是没法进行调度的
3、对于继承自NSObject类来说,如果想要动态的获取当前的属性和方法,必须在其声明前添加@objc关键字,否则也是没有办法通过Runtime API获取的
4、纯Swift类没有动态性,但在方法、属性前添加dynamic修饰,可获得动态性
5、继承自NSObject的swift类,其继承自父类的方法具有动态性,其他自定义方法、属性想要获得动态性,需要添加dynamic修饰
6、若方法的参数、属性类型为Swift特有、无法映射到OC的类型(如Character、Tuple),则此方法、属性无法添加dynamic修饰
网友评论