Swift3.0 - Runtime

以下直接分享一些封裝好的方法,喜歡自取:

import UIKit

class RunTime: NSObject {

  /// 交換方法
  ///
  /// - Parameters:
  ///   - target: 被交換的方法名
  ///   - replace: 用于交換的方法名
  ///   - classType: 所屬類型
  class func exchangeMethod(target: String,
                            replace: String,
                            class classType: AnyClass) {
    exchangeMethod(selector: Selector(target),
                   replace: Selector(replace),
                   class: classType)
  }
  /// 交換方法
  ///
  /// - Parameters:
  ///   - selector: 被交換的方法
  ///   - replace: 用于交換的方法
  ///   - classType: 所屬類型
  class func exchangeMethod(selector: Selector,
                            replace: Selector,
                            class classType: AnyClass) {
    let select1 = selector
    let select2 = replace
    let select1Method = class_getInstanceMethod(classType, select1)
    let select2Method = class_getInstanceMethod(classType, select2)
    let didAddMethod  = class_addMethod(classType,
                                        select1,
                                        method_getImplementation(select2Method),
                                        method_getTypeEncoding(select2Method))
    if didAddMethod {
      class_replaceMethod(classType,
                          select2,
                          method_getImplementation(select1Method),
                          method_getTypeEncoding(select1Method))
    }else {
      method_exchangeImplementations(select1Method, select2Method)
    }
  }

  /// 獲取方法列表
  ///
  /// - Parameter classType: 所屬類型
  /// - Returns: 方法列表
  class func methods(from classType: AnyClass) -> [Method] {
    var methodNum: UInt32 = 0
    var list = [Method]()
    let methods = class_copyMethodList(classType, &methodNum)
    for index in 0..<numericCast(methodNum) {
      if let met = methods?[index] {
        list.append(met)
      }
    }
    return list
  }

  /// 獲取屬性列表
  ///
  /// - Parameter classType: 所屬類型
  /// - Returns: 屬性列表
  class func properties(from classType: AnyClass) -> [objc_property_t] {
    var propNum: UInt32 = 0
    let properties = class_copyPropertyList(classType, &propNum)
    var list = [objc_property_t]()
    for index in 0..<Int(propNum) {
      if let prop = properties?[index]{
        list.append(prop)
      }
    }
    return list
  }

  /// 成員變量列表
  ///
  /// - Parameter classType: 類型
  /// - Returns: 成員變量
  class func ivars(from classType: AnyClass) -> [Ivar] {
    var ivarNum: UInt32 = 0
    let ivars = class_copyIvarList(classType, &ivarNum)
    var list = [Ivar]()
    for index in 0..<numericCast(ivarNum) {
      if let ivar: objc_property_t = ivars?[index] {
        list.append(ivar)
      }
    }
    return list
  }
  
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容