Skip to content

Instantly share code, notes, and snippets.

@ncreated
Last active June 5, 2020 15:32
Show Gist options
  • Save ncreated/ccf68aea1061a923e63346a70486ed52 to your computer and use it in GitHub Desktop.
Save ncreated/ccf68aea1061a923e63346a70486ed52 to your computer and use it in GitHub Desktop.
Object-oriented method swizzling
private class Locker {}
private let locker = Locker()
internal class Method {
static func `for`(selector: Selector, inClass `class`: AnyClass) -> Method? {
objc_sync_enter(locker)
if let existingSwizzling = existingSwizzlings[hash(class, selector]) {
return existingSwizzlings
}
let newSwizzling = Method(method: method)
existingSwizzlings[hash(class, selector)] = newSwizzling
objc_sync_exit(locker)
return newSwizzling
}
func set(newImplementation newIMP: IMP) {
objc_sync_enter(locker)
// do the thing
objc_sync_exit(locker)
}
}
private var existingSwizzlings: [hash(class, selector): Method] = [:]
internal class Method {
static func `for`(selector: Selector, inClass `class`: AnyClass) -> Method? {
if let existingSwizzling = existingSwizzlings[hash(class, selector]) {
return existingSwizzlings
}
let newSwizzling = Method(method: method)
existingSwizzlings[hash(class, selector)] = newSwizzling
return newSwizzling
}
func set(newImplementation newIMP: IMP) {
// do the thing
}
}
private var existingSwizzlings: [hash(class, selector): Method] = [:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment