Created
November 21, 2017 23:10
-
-
Save efremidze/c55f710b1d76825247bb394eda1d179b to your computer and use it in GitHub Desktop.
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
import ObjectiveC.runtime | |
// https://codelle.com/blog/2016/2/calling-methods-from-strings-in-swift/ | |
func extractMethod(_ owner: AnyObject, _ selector: Selector) -> ((Any?, Any?) -> AnyObject)? { | |
guard let method = getMethod(owner, selector) else { return nil } | |
let imp = method_getImplementation(method) | |
typealias CFunction = @convention(c) (AnyObject, Selector, Any?, Any?) -> Unmanaged<AnyObject> | |
let function = unsafeBitCast(imp, to: CFunction.self) | |
return { arg1, arg2 in function(owner, selector, arg1, arg2).takeUnretainedValue() } | |
} | |
private func getMethod(_ owner: AnyObject, _ selector: Selector) -> Method? { | |
if let owner = owner as? AnyClass { | |
return class_getClassMethod(owner, selector) | |
} else { | |
return class_getInstanceMethod(type(of: owner), selector) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment