Anand
Anand

Reputation: 4232

will calling removeFromSuperview twice cause a crash or side effect

I have a UIView element which I am adding to the main view controller.

Due to the design of my code, it so happens that the removeFromSuperview is called twice in different places of my code.

[myview removeFromSuperview];

That is how my code is, so I want to know if calling the 'removeFromSuperview' causes any problem.

Or how do I check if the view is in the superview and only the remove it.

e.g

if (myview in superview)
    [myview removeFromSuperview];
else
    do nothing

Upvotes: 3

Views: 2455

Answers (2)

Alex Moskalev
Alex Moskalev

Reputation: 607

Try this :

if (myView.view.superview != nil) {
    [myView removeFromSuperview];
}
else {
    //do something
}

Upvotes: -1

Denis
Denis

Reputation: 6413

The docs for the removeFromSuperview is telling the following:

If the receiver’s superview is not nil, the superview releases the receiver. If you plan to reuse a view, be sure to retain it before calling this method and release it again later as appropriate.

It means that no crash or side effect should happen, and a check you're asking about is already performed by the implementation of this method.

However, if you need to check if your view is added as subview to some other view, you can use the following code:

if( theView.superview != nil )
{
  // theView is a subview for some view
}

Upvotes: 8

Related Questions