Created
November 28, 2016 22:11
-
-
Save ygweric/c1b6399fce8296174353ce1a74406488 to your computer and use it in GitHub Desktop.
Swizzle for class method and instance method with Swift
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
func swizzleClassMethod(cls: AnyClass, oldSelector: Selector, newSelector: Selector) { | |
let oldMethod = class_getClassMethod(cls, oldSelector) | |
let newMethod = class_getClassMethod(cls, newSelector) | |
method_exchangeImplementations(oldMethod, newMethod) | |
// following code not work | |
// if(class_addMethod(cls, oldSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) { | |
// class_replaceMethod(cls, newSelector, method_getImplementation(oldMethod), method_getTypeEncoding(oldMethod)) | |
// } else { | |
// method_exchangeImplementations(oldMethod, newMethod) | |
// } | |
} | |
func swizzleInstanceMethod(cls: AnyClass, oldSelector: Selector, newSelector: Selector) { | |
let oldMethod = class_getInstanceMethod(cls, oldSelector) | |
let newMethod = class_getInstanceMethod(cls, newSelector) | |
if(class_addMethod(cls, oldSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) { | |
class_replaceMethod(cls, newSelector, method_getImplementation(oldMethod), method_getTypeEncoding(oldMethod)) | |
} else { | |
method_exchangeImplementations(oldMethod, newMethod) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment