Skip to content

Instantly share code, notes, and snippets.

@tarunon
Created January 28, 2021 07:38
Show Gist options
  • Save tarunon/0165137d25742ec34ca9dc8805ca6c0b to your computer and use it in GitHub Desktop.
Save tarunon/0165137d25742ec34ca9dc8805ca6c0b to your computer and use it in GitHub Desktop.
import Foundation
private class Weakbox {
weak var object: NSObjectProtocol?
init(_ object: NSObjectProtocol) {
self.object = object
}
}
class DelegateForwarder: NSObject {
private var delegates = [Selector: Weakbox]()
func setDelegate(delegate: NSObjectProtocol?, for selectors: [Selector]) {
if let delegate = delegate {
selectors.forEach { selector in
self.delegates[selector] = Weakbox(delegate)
}
} else {
selectors.forEach { selector in
self.delegates.removeValue(forKey: selector)
}
}
}
override func responds(to aSelector: Selector!) -> Bool {
return delegates[aSelector]?.object?.responds(to: aSelector) ?? super.responds(to: aSelector)
}
override func forwardingTarget(for aSelector: Selector!) -> Any? {
return delegates[aSelector]?.object ?? super.forwardingTarget(for: aSelector)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment