runtime

类实例方法转成block

2017-03-27  本文已影响12人  轻云绿原

运用runtime可以把一个类方法转成block

importFoundation

importUIKit

classDemo:NSObject{

functest(msg:String){

print(msg)

}

}

let sel =#selector(Demo.test(msg:))

///获取test(msg:)的方法

let method:Method=class_getInstanceMethod(Demo.self,sel)

///获取方法实现体的指针

let oldIMP:IMP=method_getImplementation(method)

//把方法体指针转成具体的block

typealiasOldBlockType =@convention(c) (Demo,Selector,String)->Void

let oldBlock =unsafeBitCast(oldIMP, to:OldBlockType.self)

//调用

oldBlock(Demo(),sel,"调用方法。")

上一篇下一篇

猜你喜欢

热点阅读