문제

I have a case in my code where it seems like I have to re-add a child node if I redefine what it's pointing to but I don't quite understand why.

For example:

_worldNode = [SKNode node];
_childNode = [SKNode node]; //set childNode to point to a node here. 
_childChildNode = [SKSpriteNode spriteNodeWithImageNamed:@"test"];

[self addChild:_worldNode]; 
[_worldNode addChild:_childNode]; //add childNode to the worldNode
[_childNode addChild:_childChildNode];

//Later on...

[_childNode removeAllChildren]; //1. do I need to do this to clean up _childChildNode first?
_childNode = [SKNode node]; //set childNode to another node.
_anotherChildChildNode = [SKSpriteNode spriteNodeWithImageNamed:@"test"];
[_childNode addChild:_anotherChildChildNode];

//2. do I need to re-add _childNode to _worldNode now?

Doing 1 seems to free up a lot of nodes in my game, but I didn't think that was necessary as I'm pointing _childNode to another node right below, so I thought the node I was originally pointing to (and _childChildNode) would have a refcount of 0 and would be deallocated?

I also don't think I need to do 2, as I've already added _childNode to _worldNode before but my game just seems to go blank if I don't add this line (probably from the removeAllChildren call).

Do you know if I'm missing something here?

도움이 되었습니까?

해결책

Doing 1 seems to free up a lot of nodes in my game, but I didn't think that was necessary as I'm pointing _childNode to another node right below, so I thought the node I was originally pointing to (and _childChildNode) would have a refcount of 0 and would be deallocated?

You need to remove _childNode from its parent:

[_childNode removeFromParent];

Until you do that, _childNode stays in memory, because parent node holds a reference to _childNode. Moreover, if you call removeFromParent, calling removeAllChildren is redundant.

After assigning a new node to _childNode, you have to add it to _worldNode again, because it is a completely new node:

_childNode = [SKNode node];
_anotherChildChildNode = [SKSpriteNode spriteNodeWithImageNamed:@"test"];
[_childNode addChild:_anotherChildChildNode];
[_worldNode addChild:_childNode];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top