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

Swizzling NSObject classes in Swift

codelynx
March 16, 2021
91

Swizzling NSObject classes in Swift

codelynx

March 16, 2021
Tweet

Transcript

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

    existing NSObject methods • UIViewController viewDidAppear UIViewController myViewDidAppear viewDidAppear Before After viewDidAppear viewDidAppear
  2. 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
  3. 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) } }
  4. Consideration • Do not abuse • Apple may terminate or

    discontinue this mechanism in the future