修改實例方法
import Foundation
import UIKit
class Demo:NSObject{
dynamic func test(msg:String){
print(msg)
}
class func test1(msg:String){
print(msg)
}
}
let sel = #selector(Demo.test(msg:))
/// 獲取test(msg:)的方法
let method:Method = class_getInstanceMethod(Demo.self, sel)
/// 獲取方法實現(xiàn)體的指針
let oldIMP:IMP = method_getImplementation(method)
// 把方法體指針轉(zhuǎn)成具體的block
typealias OldBlockType = @convention(c) (Demo,Selector,String)->Void
let oldBlock = unsafeBitCast(oldIMP, to: OldBlockType.self)
// 調(diào)用
//oldBlock(Demo(), sel, "調(diào)用方法。")
// 參數(shù)方法要把類名帶上技即,方法名不用帶著洼。帶了出錯。
let newBlock:@convention(block)(Demo,String)->Void = {(demo,msg) in
print("before")
oldBlock(demo, sel, msg)
print("after")
}
let newIMP = imp_implementationWithBlock(unsafeBitCast(newBlock, to: AnyObject.self))
method_setImplementation(method, newIMP)
Demo().test(msg: "jjj")
//結(jié)果
/*
before
jjj
after
*/
增加新的實例方法
import Foundation
import UIKit
class Demo:NSObject{
dynamic func test(msg:String){
print(msg)
}
class func test1(msg:String){
print(msg)
}
}
//方法體
typealias NewBlock = @convention(block)(Demo,Selector,String)->Void
let block:NewBlock = { (demo,sel,msg) in
print(msg)
}
//方法引用 IMP
let imp = imp_implementationWithBlock(unsafeBitCast(block, to: AnyObject.self))
//方法選擇器
let sel = Selector(("newFunc"))
//向類里增加方法
class_addMethod(Demo.self, sel, imp, "v@:")
//調(diào)用新的方法
Demo().perform(sel,with: "新增加了一個方法而叼。")
/*
新增加了一個方法身笤。
*/
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者