Cocos2d中的removeFromParent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
void Node::removeFromParent()

{

this->removeFromParentAndCleanup(true);

}

void Node::removeFromParentAndCleanup(bool cleanup)

{

if (_parent != nullptr)

{

_parent->removeChild(this,cleanup);

}

}

/* "remove" logic MUST only be on this method

\* If a class want's to extend the 'removeChild' behavior it only needs

\* to override this method

*/

void Node::removeChild(Node* child, bool cleanup /* = true */)

{

// explicit nil handling

if (_children.empty())

{

return;

}

ssize_t index = _children.getIndex(child);

if( index != CC_INVALID_INDEX )

this->detachChild( child, index, cleanup );

}





ssize_t getIndex(T object) const

{

auto iter = std::find(_data.begin(), _data.end(), object);

if (iter != _data.end())

return iter - _data.begin();

return -1;

}



void Node::detachChild(Node *child, ssize_t childIndex, bool doCleanup)
{
// IMPORTANT:
// -1st do onExit
// -2nd cleanup
if (_running)
{
child->onExitTransitionDidStart();
child->onExit();
}

// If you don't do cleanup, the child's actions will not get removed and the
// its scheduledSelectors_ dict will not get released!
if (doCleanup)
{
child->cleanup();
}

#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
sEngine->releaseScriptObject(this, child);
}
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
// set parent nil at the end
child->setParent(nullptr);

_children.erase(childIndex);
}



Node* Node::getChildByName(const std::string& name) const
{
CCASSERT(!name.empty(), "Invalid name");

std::hash<std::string> h;
size_t hash = h(name);

for (const auto& child : _children)
{
// Different strings may have the same hash code, but can use it to compare first for speed
if(child->_hashOfName == hash && child->_name.compare(name) == 0)
return child;
}
return nullptr;
}

需要remove的时候搜索到找到在Vector<Node*> _children; 中的index,然后erase掉