Extending UIViewController and Swizzling viewDidLoad

suggest change

In Objective-C, method swizzling is the process of changing the implementation of an existing selector. This is possible due to the way Selectors are mapped on a dispatch table, or a table of pointers to functions or methods.

Pure Swift methods are not dynamically dispatched by the Objective-C runtime, but we can still take advantage of these tricks on any class that inherits from NSObject.

Here, we will extend UIViewController and swizzle viewDidLoad to add some custom logging:

extension UIViewController {
    // Swift does not allow overriding +load or +initialize, and dispatch_once is gone.
    // Call swizzleViewDidLoad() once, for example at launch.
    public static func swizzleViewDidLoad() {
        struct Static {
            static let token: Void = {
                let originalSelector = #selector(UIViewController.viewDidLoad)
                let swizzledSelector = #selector(UIViewController.myViewDidLoad)
                guard let originalMethod = class_getInstanceMethod(UIViewController.self, originalSelector),
                      let swizzledMethod = class_getInstanceMethod(UIViewController.self, swizzledSelector) else {
                    return
                }
                let didAddMethod = class_addMethod(
                    UIViewController.self,
                    originalSelector,
                    method_getImplementation(swizzledMethod),
                    method_getTypeEncoding(swizzledMethod)
                )
                if didAddMethod {
                    class_replaceMethod(
                        UIViewController.self,
                        swizzledSelector,
                        method_getImplementation(originalMethod),
                        method_getTypeEncoding(originalMethod)
                    )
                } else {
                    method_exchangeImplementations(originalMethod, swizzledMethod)
                }
            }()
        }
        _ = Static.token
    }

    // Logs the name of the function. The same hook can run other code.
    @objc func myViewDidLoad() {
        // Not recursive: the selectors were exchanged above.
        // An extension cannot call super.
        self.myViewDidLoad()
        print(#function) // logs myViewDidLoad()
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents