在两个相似的子类 Objective C 之间重用代码
我有一些代码,用于在鼠标悬停在 NSTextField 上和编辑它时在 NSTextField 周围绘制边框,以及在用户键入时垂直调整其大小。我现在想在 NSTokenFieldCell 上使用此代码。我已经让它工作得很好,并且 NSTextField 和 NSTokenFieldCell 的实现是相同的。我想知道是否有某种方法可以避免在两个类类型之间重复代码。我相信 NSTokenFieldCell 实际上是 NSTextField 的子类。
I have a bit of code that I use to draw a border around a NSTextField when mousing over it, and while editing it, as well as to have it resize vertically when the user is typing. I want to use this code on an NSTokenFieldCell now. I've gotten it to work fine, and the implementation is identical for both NSTextField and NSTokenFieldCell. I was wondering if there was some way I could avoid the need to duplicate my code between the two class types. I believe NSTokenFieldCell is actually a subclass of NSTextField.
我最终将所有自定义功能提取到一个单独的 NSObject 类中,然后为我的 NSTextField 和 NSTokenField 类提供了它的实例,然后我只是使用 - (id)forwardingTargetForSelector 将所有自定义逻辑代理到我的“逻辑”对象中:(SEL)aSelector
它并不完美,因为我仍然需要手动代理我覆盖的方法,例如每个类中的drawRect,但我想说它现在属于“足够好”类别。我有兴趣看看是否有人有更好的解决方案我可以尝试。
I ended up pulling all my custom functionality out into a separate NSObject class, and then gave both my NSTextField and NSTokenField classes an instance of it, then I just proxied all of the custom logic into my "logic" object using - (id)forwardingTargetForSelector:(SEL)aSelector
It's not perfect as I still need to manually proxy over the methods that I overrode such as drawRect in each class, but I'd say it falls into the "good enough" category now. I'm interested to see if anyone has a better solution I can try.