Skip to content

Instantly share code, notes, and snippets.

@neobeppe
Created December 5, 2023 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neobeppe/a3a9021299b1ee21afa687c65a762a59 to your computer and use it in GitHub Desktop.
Save neobeppe/a3a9021299b1ee21afa687c65a762a59 to your computer and use it in GitHub Desktop.
Method injection playground
//: Playground - noun: a place where people can play
import Foundation
//Class A implements a method that says its name
class ClassA {
@objc
func hello() {
print("Hello, i'm " + String(describing: type(of: self)))
}
}
//Class B is empty
class ClassB { }
//Inject method from one class in another one
func useMethod(sel: Selector, fromClass: AnyClass, inObject: AnyObject) {
guard let meth = class_getInstanceMethod(fromClass, sel) else {
return
}
typealias ClosureType = @convention(c) (AnyObject, Selector) -> Void
let imp = method_getImplementation(meth)
let callMethod: ClosureType = unsafeBitCast(imp, to: ClosureType.self)
callMethod(inObject, sel)
}
//A
let a = ClassA()
a.hello()
//A hello method in B
let b = ClassB()
useMethod(sel: #selector(ClassA.hello), fromClass:ClassA.self, inObject: b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment