Last active
November 23, 2017 09:10
-
-
Save vvit/d9afec77fb8333686cdb894ab5a14b1e to your computer and use it in GitHub Desktop.
Swizzling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// AppDelegate | |
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { | |
UIViewController.doSwizzleStuff() | |
} | |
// extension | |
// MARK: - Swizzling | |
private var hasSwizzled = false | |
extension UIViewController { | |
final public class func doSwizzleStuff() { | |
guard !hasSwizzled else { return } | |
hasSwizzled = true | |
// make sure this isn't a subclass | |
if self !== UIViewController.self { | |
return | |
} | |
let originalSelector = #selector(viewDidLoad) | |
let swizzledSelector = #selector(my_viewDidLoad) | |
let originalMethod = class_getInstanceMethod(self, originalSelector) | |
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) | |
guard originalMethod != nil, swizzledMethod != nil else { | |
return | |
} | |
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) | |
if didAddMethod { | |
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!)) | |
} else { | |
method_exchangeImplementations(originalMethod!, swizzledMethod!) | |
} | |
} | |
// MARK: - Method Swizzling | |
@objc func my_viewDidLoad() { | |
self.my_viewDidLoad() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment