修改实例方法
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)
/// 获取方法实现体的指针
let oldIMP:IMP = method_getImplementation(method)
// 把方法体指针转成具体的block
typealias OldBlockType = @convention(c) (Demo,Selector,String)->Void
let oldBlock = unsafeBitCast(oldIMP, to: OldBlockType.self)
// 调用
//oldBlock(Demo(), sel, "调用方法。")
// 参数方法要把类名带上,方法名不用带。带了出错。
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")
//结果
/*
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@:")
//调用新的方法
Demo().perform(sel,with: "新增加了一个方法。")
/*
新增加了一个方法。
*/