objective-cuiviewsuperview

Self-deallocating by calling removeFromSuperview on itself?


Would calling removeFromSuperview in a customized UIView as [self removeFromSuperview] correctly remove itself from its super view just like doing [self.customView removeFromSuperview] in its super view?

I've checked and it does seem to do the same but I'd still like to make sure!


Solution

  • Sure. How a UIView instance receives the removeFromSuperview message is irrelevant – it will do exactly the same thing whether it was called from outside or within the instance.

    The view will also get deallocated in the exact same way after being removed from the superview, as long as there are no other strong references to it. If you want, you can test it yourself by implementing the dealloc method in your view's subclass, and adding an NSLog or a breakpoint to it.

    The only notable exception for when you can call removeFromSuperview is you should never call it from within the view's drawRect: method, as stated in the documentation. Doing so would lead to undefined behaviour.