3

I am about to do a

[vistaX removeFromSuperview];

How do I test to see if vistaX is present on the super view before removing it? Removing a view that isn't there would lead to a crash on the application...

thanks for any help.

Duck
  • 34,902
  • 47
  • 248
  • 470
  • http://stackoverflow.com/questions/2777438/how-to-tell-if-uiviewcontrollers-view-is-visible/2777460#2777460 – LolaRun Nov 29 '11 at 21:28

2 Answers2

14

You can guard it with:

if(vistaX.superview)
     [vistaX removeFromSuperview];

Although, I wasn't aware that removeFromSuperview would fail if there wasn't a superview. Are you sure that this is the issue and it isn't maybe related to the fact that removeFromSuperview releases the view?

EDIT: Based on your comment below, it sounds like vistaX's retain count is going to 0 the first time around and it's being freed. If you don't want this to happen, add a property to your class that retains vistaX (i.e. "@property (retain)") so you can be sure that it'll always be around.

EDIT EDIT: Do you have a handle on the superView or one of its ancestors? If so, I would recommend setting a unique tag on the vistaX view. This can be done programmatically or through IB. Then, use the viewWithTag selector on one of the ancestors to search for the vistaX view by its unique tag.

Chris Karcher
  • 2,252
  • 7
  • 24
  • 31
  • thanks but the application is still crashing with your code. It is now crashing on the IF. The problem is that the method where this line is, is called two times. The first time it is called vistaX exists, then it is removed from superview. The second time, vistaX is not anymore on the superview. Then, even the test (vistaX.superview) is crashing... I thought it would give me a false on the IF, but it is not allowing the IF to go. – Duck Oct 14 '09 at 18:42
  • If you (Mike) get an EXC_BAD_ACCESS error, than the last stated by Chris is probably the case, indeed. If `vistaX` is an instance variable, make sure you have the ownership of it (that is, you have retained the object so it will exist as long as you *may* use it) <- Some memory management basics, I know it's very limited. – Joost Oct 14 '09 at 18:44
  • no, I think I am not being able to explain what I want.... and I will rephrase my question... the question is: is it possible to test for an existence of a view even if the view do not exists anymore? Something like "is there any view named vistaX in the superview?" If there's no view, then I receive a false. – Duck Oct 14 '09 at 20:35
  • If you vistaX a unique tag (as Chris suggests), then you can use `[superview viewForTag:]` to look for it. If that method returns nil, there is no subview in superview with that tag. – Sixten Otto Oct 14 '09 at 21:52
2

You Can Check it By applying one condition like

if(vistaX.superview!=nil)
   [vistaX removeFromSuperview];

then if superview exists, it will remove from super view, otherwise not.

Sanoj Kashyap
  • 5,020
  • 4
  • 49
  • 75