Your question is equivalent to the following: *Given a cellular inclusion $i : X\to Y$, when is there a retraction $r:Y \to X$?* (Being a retraction means that $r\circ i: X\to X$ is the identity.) The answer is usually phrased in terms of obstruction theory. For simplicity, let's assume that $Y$ is a finite complex obtained from $X$ by attaching a single $j$-cell, i.e., $Y = X \cup_f D^j$, where $f: S^{j-1} \to X$ is the attaching map. Assume also that $X$ is a based space an $f$ is a based map. In this case, it is easy to check that the desired retraction $r: Y \to X$ exists if and only if the homotopy class $[f] \in \pi_{j-1}(X)$ vanishes. We can think of this class as an obstruction lying in $$ \theta \in H^j(Y,X;\pi_{j-1}(X)) $$ (the $j$-cohomology group of the pair $(Y,X)$ with coefficients in $\pi_{j-1}(X)$). Now, in the general case, we inductively assume that a retraction $$r_{j-1}: X_j \cup_{X_{j-1}} Y_{j-1}\to X$$ has already been specified where $Y_{j-1}$ is $(j-1)$-skeleton of $Y$. We wish to extend the retraction to $Y_j$. For every cell of $Y_j$ that is not lying in $X$, we have an obstruction in $\pi_{j-1}(X)$ defined as above. If we vary the cells, we obtain an element of $$ H^j(Y_j,Y_{j-1} \cup X_j ;\pi_{j-1}(X)) $$ whose vanishing is both necessary and sufficient to finding an extension $r_j: X \cup Y_{j} \to X$. Notice that the displayed cohomology group is the *cellular $j$-cochains* of the pair $(Y,X)$ with coefficients in $\pi_{j-1}(X)$. It turns out that the element in question is a cocycle in this cochain complex. However, notice we made a choice: suppose we had used a different $r_{j-1}$? Then the obstruction can change. With a little effort one can eventually see that the obstruction changes by a coboundary. So if we take into account all the choices, the cocycle is defined only up to a coboundary. The upshot: there is a sequence of obstructions $$ \theta_j \in H^j(Y,X;\pi_{j-1}(X)) $$ such that $\theta_j$ is defined when $\theta_{j-1}$ vanishes. Furthermore all the obstructions vanish iff a retraction $Y\to X$ exists.