Is there any (best practice) way within the class to hook the events when a SKSpriteNode (or SKNode) is added onto and removed from a parent node?
Kobold Kit adds the callback methods didMoveToParent
and willMoveFromParent
to all KK*Node classes.
This is achieved by subclassing all SK*Node classes and overriding the corresponding addChild
and removeChild
methods and their variants. They then call the category methods above on the node, depending on whether the node was added or removed.
Unfortunately we can not subclass SKNode in order to add methods to all SKNode classes - all the other SK*Node will still have the original SKNode as its parent. Besides subclassing you could also add custom addChild/removeChild methods (let's say addNode/removeNode) in an SKNode category and use only these. They would then send a willAdd/didRemove message to the node before calling the original addChild/removeChild implementation.
Theoretically this could also be done by swizzling the addChild/removeChild methods on the SKNode class. But if I remember correctly that's what I initially tried, and it didn't work - I don't remember why exactly, one of the reasons could have been that subclasses of SKNode could implement their own versions of addChild/removeChild without calling the super implementation, or calling the super implementation simply does not run the swizzled methods. Another reason might be that internally the addChild/removeChild methods are directly forwarded to the underlying C++ Sprite Kit engine rather than being passed upwards in the SKNode class hierarchy.