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'-init
method, 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
-doFoo
and-doBar
as if they were implemented by widget, even though the messages are being forwarded to one of its trait objects:(Edit: Added error handling.)
Traits or Mixins are not supported by Objective-C, you only have built-in option of Categories. But fortunately Objective-C Runtime has almost all tools for implementing own idea if mixing or traits with adding methods and properties to your class at runtime. You can read more about opportunities which Objective-C Runtime provides for you on Apple's documentation website Objective-C Runtime Docs
The idea is:
1) You can create an Objective-C protocol (Mixin), in which you will declare properties and methods.
2) Then you create a class (Mixin implementation), which will implement methods from this protocol.
3) You make your some class, in which you want to provide the possibility of composition with mixins, to conform that protocol (Mixin).
4) When your application launches, you add with Objective-C runtime all implementations from (Mixin implementation) class and properties declared in (Mixin) into your class.
5) voilà :)
Or you can use some ready open source projects such as "Alchemiq"
You're probably looking for categories. See http://macdevelopertips.com/objective-c/objective-c-categories.html.