HDRunTime.swift 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. //
  2. // HDRunTime.swift
  3. // HDEmptyViewDemo
  4. //
  5. // Created by liuyi on 2018/5/24.
  6. // Copyright © 2018年 liuyi. All rights reserved.
  7. //
  8. import UIKit
  9. import Foundation
  10. struct HDRunTime {
  11. /// 交换方法
  12. /// - Parameters:
  13. /// - selector: 被交换的方法
  14. /// - replace: 用于交换的方法
  15. /// - classType: 所属类型
  16. static func exchangeMethod(selector: Selector,
  17. replace: Selector,
  18. class classType: AnyClass) {
  19. let select1 = selector
  20. let select2 = replace
  21. let select1Method = class_getInstanceMethod(classType, select1)
  22. let select2Method = class_getInstanceMethod(classType, select2)
  23. guard (select1Method != nil && select2Method != nil) else {
  24. return
  25. }
  26. let didAddMethod = class_addMethod(classType,
  27. select1,
  28. method_getImplementation(select2Method!),
  29. method_getTypeEncoding(select2Method!))
  30. if didAddMethod {
  31. class_replaceMethod(classType,
  32. select2,
  33. method_getImplementation(select1Method!),
  34. method_getTypeEncoding(select1Method!))
  35. }else {
  36. method_exchangeImplementations(select1Method!, select2Method!)
  37. }
  38. }
  39. /// 获取方法列表
  40. ///
  41. /// - Parameter classType: 所属类型
  42. /// - Returns: 方法列表
  43. static func methods(from classType: AnyClass) -> [Method] {
  44. var methodNum: UInt32 = 0
  45. var list = [Method]()
  46. let methods = class_copyMethodList(classType, &methodNum)
  47. for index in 0..<numericCast(methodNum) {
  48. if let met = methods?[index] {
  49. list.append(met)
  50. }
  51. }
  52. free(methods)
  53. return list
  54. }
  55. /// 获取属性列表
  56. ///
  57. /// - Parameter classType: 所属类型
  58. /// - Returns: 属性列表
  59. static func properties(from classType: AnyClass) -> [objc_property_t] {
  60. var propNum: UInt32 = 0
  61. let properties = class_copyPropertyList(classType, &propNum)
  62. var list = [objc_property_t]()
  63. for index in 0..<Int(propNum) {
  64. if let prop = properties?[index]{
  65. list.append(prop)
  66. }
  67. }
  68. free(properties)
  69. return list
  70. }
  71. /// 成员变量列表
  72. ///
  73. /// - Parameter classType: 类型
  74. /// - Returns: 成员变量
  75. static func ivars(from classType: AnyClass) -> [Ivar] {
  76. var ivarNum: UInt32 = 0
  77. let ivars = class_copyIvarList(classType, &ivarNum)
  78. var list = [Ivar]()
  79. for index in 0..<numericCast(ivarNum) {
  80. if let ivar: objc_property_t = ivars?[index] {
  81. list.append(ivar)
  82. }
  83. }
  84. free(ivars)
  85. return list
  86. }
  87. }