Are there any techniques for emulating traits or mixins in Objective-C?
In Scala, for example, I can do something like this:
trait ControllerWithData {
def loadData = ...
def reloadData = ...
def elementAtIndex = ...
}
trait ControllerWithStandardToolbar {
def buildToolbar = ...
def showToolbar = ...
def hideToolbar = ...
}
class MyTableController extends ControllerWithData
with ControllerWithStandardToolbar {
def loadView = {
super.loadView
loadData
buildBar
}
}
It’s basically a way to combine (or mix in) multiple pieces of functionality into a single class. So right now I have kind of an all-purpose UIViewController that all of my controllers subclass from, but it would be neater if I could break that down and have specific controllers inherit specific behavior.
There’s no direct language support, but you could accomplish something similar with message forwarding. Let’s say you have trait classes “Foo” and “Bar”, which define methods “
-doFoo” and “-doBar“, respectively. You could define your class to have traits, like this:Now, you can create instances of MyClassWithTraits, and add whatever “trait” objects you’d like:
You could make these calls to
-addTrait:in MyClassWithTraits’-initmethod, if you want every instance of that class to have the same kind of traits. Or, you could do it like I’ve done here, which allows you to assign a different set of traits to each instance.And then you can call
-doFooand-doBaras if they were implemented by widget, even though the messages are being forwarded to one of its trait objects:(Edit: Added error handling.)