How to check if CALayer exists
I have a CALayer which animates (moves) off-screen on the y axis.
After it's off-screen i'm doing a [myLayer removeFromSuperLayer]
so开发者_如何学Python its gone from the view and does not go back to start position.
While the layer is still in the view it can be paused and resumed by pushing a toggle button and this works all fine.
The only thing is that after the [myLayer removeFromSuperLayer]
has run my app crashes.
This is caused by the fact the button is trying to pause or resume the layer which doesn't exist anymore.
How can i check if the layer is removed or still in the view?
I thought something like this for the pause part of my toggle button:
if (self.myLayer == nil)
{
// here i want to add the layer again
[self.view.layer addSublayer:myLayer];
// immediately pause it
[self pauseLayer:myLayer];
}
else
{
// just pause no need to create the layer again because it's still there
[self pauseLayer:myLayer];
}
As you might suspect the self.myLayer == nil
is not the way to do it, but what is?
Thanks in advance.
Removing a layer from its superlayer will not cause the layer to become nil, which is why your self.myLayer == nil
check is not working. However, you could easily set the field to nil when you remove it, like:
[self.myLayer removeFromSuperLayer];
self.myLayer = nil;
Of course, if you need to add it again after that then you'd need to either reassign the layer to self.myLayer
(if you have a reference to it that you're keeping somewhere else) or create a new instance of the layer from scratch.
精彩评论