Swift-Runtime 基本應(yīng)用

使用Swift編程,未免會(huì)使用到Runtime,下面是Swift-RunTime的基本使用,希望對(duì)大家有所幫助。

1. Runtime擴(kuò)展屬性

以UIView擴(kuò)展 loadingViewblankPageView 屬性為例
  private struct AssociatedKeys{
        
        static var loadingViewKey:LGLoadingView?
        static var blankPageViewKey:LGBlankView?
        
    }
    
    var loadingView: LGLoadingView? {
        get { return objc_getAssociatedObject(self, &AssociatedKeys.loadingViewKey) as? LGLoadingView }
        set {
            if let newValue = newValue {
            objc_setAssociatedObject(self, &AssociatedKeys.loadingViewKey, newValue,objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
            
        }
    }
    
    var blankPageView: LGBlankView? {
        get { return objc_getAssociatedObject(self, &AssociatedKeys.blankPageViewKey) as? LGBlankView }
        set {
            if let newValue = newValue {
            objc_setAssociatedObject(self, &AssociatedKeys.blankPageViewKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }


2. Runtime Swizzle方法

以交換UIViewController的生命周期方法為例
extension UIViewController{
    public override static func initialize() {
        struct Static {
            static var token: dispatch_once_t = 0
        }
        
        // 確保不是子類
        if self !== UIViewController.self {
            return
        }
        dispatch_once(&Static.token) {
          
        mySwizzle(self, origSEL: #selector(UIViewController.viewWillAppear), newSEL: #selector(UIViewController.customViewWillAppear))
        mySwizzle(self, origSEL: #selector(UIViewController.viewWillDisappear), newSEL: #selector(UIViewController.customViewWillDisappear))
        mySwizzle(self, origSEL: #selector(UIViewController.viewDidAppear), newSEL: #selector(UIViewController.customViewDidAppear))
            
        }
    }
    
    func customViewWillAppear(animated: Bool) {
        self.customViewWillAppear(animated)
   
    }
    
    func customViewWillDisappear(animated: Bool){
       
        if self.navigationItem.backBarButtonItem == nil
            && self.navigationController?.viewControllers.count > 1 {
            
            self.navigationItem.backBarButtonItem = self.backButton()
            
        }
        self.customViewWillDisappear(animated)

    }
    
    
     func customViewDidAppear(animated: Bool) {
        self.customViewDidAppear(animated)
    }
    
    //交換方法
    class func mySwizzle(cls:AnyClass,origSEL:Selector,newSEL:Selector){
        
        let originalMethod = class_getInstanceMethod(cls, origSEL)
        let swizzledMethod = class_getInstanceMethod(cls, newSEL)
        
        let didAddMethod = class_addMethod(cls, origSEL, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
        
        if didAddMethod {
            class_replaceMethod(cls, newSEL, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
        
        
    }
    
    //返回按鈕
    func backButton() -> UIBarButtonItem {
        let  temporaryBarButtonItem = UIBarButtonItem()
        temporaryBarButtonItem.title = "返回"
        temporaryBarButtonItem.target = self
        if temporaryBarButtonItem.respondsToSelector(#selector(UIBarItem.setTitleTextAttributes(_:forState:))) {
            let textAttributes = [NSFontAttributeName:UIFont.boldSystemFontOfSize(17),
                                  NSForegroundColorAttributeName:UIColor.whiteColor()
                                  
                                  ]
            UIBarButtonItem.appearance().setTitleTextAttributes(textAttributes, forState: .Normal)
            
        }
        
        temporaryBarButtonItem.action = #selector(UIViewController.goBack)
        return temporaryBarButtonItem;

    }
    
    func goBack() {
        self.navigationController?.popViewControllerAnimated(true)
    }

}

3.RunTime 獲取對(duì)象的所有屬性名和屬性值和獲取對(duì)象的所有方法名

func allPropertyNamesAndValues() ->[String: AnyObject] {
    var count: UInt32 = 0
    let properties = class_copyPropertyList(Person.self, &count)

    var resultDict: [String: AnyObject] = [:]
    for var i = 0; i < Int(count); ++i {
      let property = properties[i]

      // 取得屬性名
      let name = property_getName(property)
      if let propertyName = String.fromCString(name) {
        // 取得屬性值
        if let propertyValue = self.valueForKey(propertyName) {
          resultDict[propertyName] = propertyValue
        }
      }
    }

    return resultDict
}

func allMethods() {
  var count: UInt32 = 0
  let methods = class_copyMethodList(Person.self, &count)

  for var i = 0; i < Int(count); ++i {
    let method = methods[i]
    let sel = method_getName(method)
    let methodName = sel_getName(sel)
    let argument = method_getNumberOfArguments(method)

    print("name: (methodName), arguemtns: (argument)")
  }
}
后語(yǔ):保劍鋒從磨礪出,梅花香自苦寒來(lái)。。。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,408評(píng)論 4 61
  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,068評(píng)論 0 9
  • 從沒想過我能在29歲時(shí)成為兩個(gè)孩子的媽媽,大的23個(gè)月,小的2個(gè)月,總的來(lái)說(shuō),開心雙倍,操的心自然也是雙倍。 回頭...
    團(tuán)媽媽和圓媽媽閱讀 365評(píng)論 0 0
  • 王者榮耀已經(jīng)玩了一年了,還在黃金排位~ 想找個(gè)大神親自教我上王者。
    andy1221閱讀 171評(píng)論 0 0
  • 今天中午抽空出來(lái)約鵑兒一起午飯,這是我們比較常見的在工作日的中午與她小聚。不比以前在學(xué)校,時(shí)間就像沙子一抓一大把,...
    好馨勤閱讀 253評(píng)論 0 0

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