is it possible to do something like this in objective-c (using categories or something similar):
(pseudo code)
abstract class Element extends Node {}
class Object extends Element (and uses Sprite instead of Node) {}
class Sprite extends Node {}
One solution would be to put Node as a member variable to Element, but then i would have to write all the wrapper functions for Node class. Is it possible to extend it somehow?
thanks!
This used to be possible, but the necessary function (
class_setSuperclass) was deprecated a long time ago and cannot be used anymore (which is probably a good thing).There are a couple of different ways to go about this, some better than others.
The best, I think, would be to make a new
Elementsubclass, calledSpriteElement, which has aSpritemember variable, and then forwards on all the relevant sprite-ly methods to the internalSpriteinstance.You could also define a new protocol that captures all of the things you want about a
Sprite, like so:(I’m assuming that the
Spriteclass declares a-doSpritelyThingmethod)Then, with a category, you could declare that the
Elementclass conforms to the<Sprite>protocol:And them implement the method like so:
You would probably also want to declare that the
Spriteclass conforms to theSpriteprotocol:Then in your code, instead of declaring your variables as type
Element *, you’d declare them asid<Sprite>(any object that understands messages from the<Sprite>protocol).The first approach is fine if you can be flexible with an
Elementbeing a different instance from aSprite. If you can’t, then the second approach works great, too.