在项目升级swift3.0中发现 dynamicType属性被移动,换成type(of:) 但是之前的
class_getInstanceMethod()确得到方法,始终为nil
如 :
let selector =NSSelectorFromString("get")
//let selector =NSSelectorFromString("get:")
let method=class_getInstanceMethod(type(of:owner),selector)
此问题正在解决中,请大家给出指导意见
class_getInstanceMethod得到类的实例方法
class_getClassMethod得到类的类方法
其它:method_exchangeImplementations进行方法交换 指针
已解决:
swift 3.0 selector方法有所变化 #selector() 方法,可以先写一个写一个例子测试一下正常自己要动态调用的方法的sel方法值,如下,调试查看sel的值,就可以看到方法应当怎样拼写
一般是:方法名+With+首参+“:”+二参+“:”+N参+“:”-------注意首参首字母要大写-------------------
不过我在调用时,有一个方法调用时却没有添国With,其它大部分有With具体原因还在查找中....
另外接收方法的参数定义时注意后面加?或!防止 class_getInstanceMethod(type(of:owner),selector)方法给变量进行nil初始化的异常,
如 let mymethod? = class_getInstanceMethod(type(of:owner),selector)
然后下面的代码用
guard 进行防止unrap 的过滤
如 guard mymethod != nil else
{
return
}
..... 此处代码就可以安心执行了...
------测试---正式环境中--
// let mysys:SystemService = SystemService()
// let sel:Selector = #selector(SystemService.signOn(context:))
// let mysyssigon = class_getInstanceMethod(type(of: mysys), sel)
------playgroud demo-------
//: Playground - noun: a place where people can play
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//@objc
class MyClass:NSObject {
fileprivate static let aa = 100
required override init() {
print("Hello, world11")
}
func mymethod00(a:Int)
{
print("method is me")
}
public func mymethod()
{
print("method is me")
}
public func mymethod(a:Int)
{
print("method a is me \(a)")
}
public func mymethod(a:Int,b:Int)
{
print("method is a:\(a) ,b:\(b) ")
}
static func staticmethod()
{
print("mehod is static method")
}
}
//type.method()
//let sel=Selector("method:")
/*
func myFun(a:Int)
{
print("this a:\(a)")
}
let myf=myFun(a:)
myf(300)
myf(400)
*/
/*
let sel22 = Selector("methodWitha:")
let mymethod01 = class_getInstanceMethod(type(of:MyClass()), sel22)
*/
let mytype = MyClass()
//一个参数方法
//let myf01 = mytype.method(a:)
//myf01(200)
//0个参数方法
let mymethod = mytype.mymethod()
//mymethod;
//2个参数方法
let Sel2:Selector = #selector(MyClass.mymethod as (MyClass) -> () -> ())
let mymethodtwo = class_getInstanceMethod(type(of: mytype), Sel2)
//let mymethodtwo = class_getInstanceMethod(type(of: mytype), Sel2)
mymethodtwo;
let Sel22:Selector = #selector(MyClass.mymethod(a:))
let mymethodtwo22 = class_getInstanceMethod(type(of: mytype), Sel22)
mymethodtwo22;
let Sel33:Selector = #selector(MyClass.mymethod(a:b:));
let mymethodtree = class_getInstanceMethod(type(of: mytype), Sel33);
mymethodtree;
//mymethodtwo(100,200)
//0 私有方法
let sel00:Selector = #selector(MyClass.mymethod00(a:))
let mymethodinstance00 = class_getInstanceMethod(type(of: mytype), sel00)