Skip to content

Instantly share code, notes, and snippets.

@alexj70
Created April 28, 2017 08:26
Show Gist options
  • Save alexj70/67394c03a2229aa1ae6c75b2ba96f9ba to your computer and use it in GitHub Desktop.
Save alexj70/67394c03a2229aa1ae6c75b2ba96f9ba to your computer and use it in GitHub Desktop.
Method Swizzling

Method Swizzling

★ Replacement of viewWillAppear method

private let swizzling: (UIViewController.Type) -> () = { viewController in
    
    let originalSelector = #selector(viewController.viewWillAppear(_:))
    let swizzledSelector = #selector(viewController.proj_viewWillAppear(animated:))
    
    let originalMethod = class_getInstanceMethod(viewController, originalSelector)
    let swizzledMethod = class_getInstanceMethod(viewController, swizzledSelector)
    
    method_exchangeImplementations(originalMethod, swizzledMethod)
}

extension UIViewController {
    
    open override class func initialize() {
        // make sure this isn't a subclass
        guard self === UIViewController.self else { return }
        swizzling(self)
    }
    
    // MARK: - Method Swizzling
    
    func proj_viewWillAppear(animated: Bool) {
        self.proj_viewWillAppear(animated: animated)
        
        let viewControllerName = NSStringFromClass(type(of: self))
        print("viewWillAppear: \(viewControllerName)")
    } 
}

★ Replacement of NSObjectProtocol.description method 

import UIKit
import ObjectiveC

extension NSObject {
    func swizzDescription() -> String {
        print("swizzed")
        return self.swizzDescription()
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    override class func initialize() {
        let m1 = class_getInstanceMethod(NSObject.self, #selector(getter: NSObjectProtocol.description))
        let m2 = class_getInstanceMethod(NSObject.self, #selector(NSObject.swizzDescription))
        
        method_exchangeImplementations(m1, m2)
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        print(self)
        return true
    }
}

★ Original: KentarouKanno/Method Swizzling.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment