Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Swizzling NSObject classes in Swift

79874cedccd1cf5baa8cb264b5091ee6?s=47 codelynx
March 16, 2021
19

Swizzling NSObject classes in Swift

79874cedccd1cf5baa8cb264b5091ee6?s=128

codelynx

March 16, 2021
Tweet

Transcript

  1. Swizzing NSObject classes Kaz Yoshikawa FEB 2021

  2. Swizzling • To be able to replace or to override

    existing NSObject methods • UIViewController viewDidAppear UIViewController myViewDidAppear viewDidAppear Before After viewDidAppear viewDidAppear
  3. What’s for? • Analytics for user tracking • eg. Logging

    extra information of all viewDidAppear methods • Application wide behavior changes • Tap on UIButton to speech before sendAction() get invoked
  4. Example func swizzleMethod(_ `class`: AnyClass, _ original: Selector, _ swizzled:

    Selector) { if let original = class_getInstanceMethod(`class`, original), let swizzled = class_getInstanceMethod(`class`, swizzled) { method_exchangeImplementations(original, swizzled) } else { print("failed to swizzle: \(`class`.self), '\(original)', '\(swizzled)'") } } swizzleMethod( UIViewController.self, #selector(UIViewController.viewDidAppear(_:)), #selector(UIViewController.viewDidAppear_x(_:)) ) public extension UIViewController { @objc private func viewWillAppear_x(_ animated: Bool) { print(Self.self, #function) self.viewWillAppear_x(animated) } }
  5. Consideration • Do not abuse • Apple may terminate or

    discontinue this mechanism in the future
  6. Code • https://gist.github.com/codelynx/3685e0530607746a0811dfd3d1fe ff 9e

  7. Thank you