AOP Aspects Swift實踐

Aspect Oriented Programming (面向切面編程)

先來看WikiPedia對AOP介紹:

AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself, instead separately specifying which code is modified via a "pointcut" specification.

這句話是說把一些與主邏輯無關的瑣碎事務分離出來,作為獨立的模塊。在 Objective-C 的世界里,就可以利用 Runtime 特性給指定的方法添加自定義代碼。實現(xiàn) AOP 有多種方式 ,Method Swizzling(Swift中使用Method Swizzling) 是其中之一,現(xiàn)在有一些第三方庫可以讓你不需要了解 Runtime ,就能直接開始使用 AOP, 如Aspects

Aspects使用Demo

對所有ViewController里面viewDidLoad,都加上一些配置,可以寫一個extension:

extension UIViewController {
    func SSViewDidLoad() {
        self.navigationController?.navigationBar.translucent = true// iOS7使用appearance設置translucent會crash
        print("SSViewDidLoad")
        self.view.backgroundColor = UIColor.whiteColor()
        if self.respondsToSelector("edgesForExtendedLayout") {
            self.edgesForExtendedLayout = .None
        }
    }
}

寫一個結構體AppConfig,寫一個靜態(tài)方法SSViewControllerConfig:

static func SSViewControllerConfig() {
        let wrappedBlock:@convention(block) (AspectInfo)-> Void = { aspectInfo in
            let instance = aspectInfo.instance() as? UIViewController
            instance?.SSViewDidLoad()
            }
        let wrappedObject: AnyObject = unsafeBitCast(wrappedBlock, AnyObject.self)
        do {
            try UIViewController.aspect_hookSelector("viewDidLoad", withOptions: .PositionAfter, usingBlock: wrappedObject)
        } catch {
            print(error)
        }
    }

然后在AppDelegate里面的AppConfig.SSViewControllerConfig()調用來看aspect_hookSelector方法,這是Aspects庫提供的,注意到usingBlock后面的參數(shù)是AnyObject, 需要用unsafeBitCase對block轉一下。

后記

Swift本身沒有Runtime,是利用的 objective-C Runtime 特性。對于 Aspect Oriented Programming ,面向切面編程,能夠很好的獨立出模塊而不影響全局邏輯,對ViewController的配置是其中一個應用,還有其它如打Log等。

微信公眾號

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

相關閱讀更多精彩內容

友情鏈接更多精彩內容