Swift监听方法耗时

封装监听方法耗时操作
开始算法练习之旅
Swift LeetCode 算法实现(2022持续更新)

基类 Core.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import Foundation

class Core: NSObject {

required override init() {
super.init()
swizzle_class(clz: object_getClass(self), originalSelector: #selector(run), swizzledSelector: #selector(run_swizzle))
}

@objc dynamic func run() {
fatalError("需实现run方法并且不要调用父类方法")
}

@objc dynamic func run_swizzle() {
print("开始执行 --> \(object_getClass(self)!)")
let startTimeInterval = Date().timeIntervalSince1970 * 1000
run_swizzle()
let endTimeInterval = Date().timeIntervalSince1970 * 1000
print(String(format: "运行耗时 --> %.3f毫秒", endTimeInterval - startTimeInterval))
}

@objc static func run() {
let object = self.init()
object.run()
}

}

func swizzle_class(clz: AnyClass?, originalSelector: Selector, swizzledSelector: Selector) {
let originalMethod = class_getInstanceMethod(clz, originalSelector)
let swizzledMethod = class_getInstanceMethod(clz, swizzledSelector)
let didAddMethod: Bool = class_addMethod(clz, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
if didAddMethod {
class_replaceMethod(clz, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
}

调用方 main.swift

1
剑指_Offer_09_用两个栈实现队列.run()

算法实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class CQueue {

private var stackAdd: [Int]
private var stackRemove: [Int]

init() {
stackAdd = []
stackRemove = []
}

func appendTail(_ value: Int) {
if stackAdd.count > 10000 {
// fatalError("数据太多")
}
stackAdd.append(value)
}

func deleteHead() -> Int {
if stackAdd.isEmpty {
return -1
} else {
stackRemove = stackAdd.reversed()
}
stackAdd.removeFirst()
return stackRemove.removeLast()
}
}

class 剑指_Offer_09_用两个栈实现队列: Core {

override func run() {
let obj = CQueue()
print(obj.deleteHead())
obj.appendTail(5)
obj.appendTail(2)
print(obj.deleteHead())
print(obj.deleteHead())
}

}

Swift中实现方法交换须满足条件:

  1. 类必须继承自NSObject
  2. 被交换的两个方法,必须用dynamic关键字标记