开发者

Checking if viewWithTag exists before removingFromSuperview

开发者 https://www.devze.com 2023-03-29 00:50 出处:网络
Is it safe to use [[self.view viewWithTag:999] removeFromSuperview]; without checking if the view actually exists开发者_JAVA百科?

Is it safe to use [[self.view viewWithTag:999] removeFromSuperview]; without checking if the view actually exists开发者_JAVA百科?

There is no error on simulator but will it cause no problem on a real device?

Is there any drawback of not using such condition?


It is completely alright to call [[self.view viewWithTag:999] removeFromSuperview]; directly. If the view exists then [self.view viewWithTag:999] will return the view and it will be removed from its superview. If the view doesn't exists then [self.view viewWithTag:999] will return nil and passing any message to nil wont take any effect.

So, in your case, there is no need to check whether the view actually exists or not.


Answer from the apple docs for UIView

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.

Never call this method from inside your view’s drawRect: method.

Nothing will happen when the view with the tag will return nil.

0

精彩评论

暂无评论...
验证码 换一张
取 消