how to remove an object only if it exists on iPhone SDK?

how to remove an object only if it exists on iPhone SDK?

I want to remove a UILabel from the UIView dynamically. There are some branching and looping, and in the end when I remove it by 'removeFromSuperview' sdk crashes as it doesn't exist anymore, in some cases.

[lbl_timer removeFromSuperview]; 

So what i wanted is simply how to know if an object exists?


Embedding WebView in UIView


Problem sending Apple Push Notification using Java and REST
You'll really need to clarify in what sense you mean by "exists" as this must be interpreted in various ways.. Given a view, how do I get its viewController? You may find this an object's retainCount may satisfy your definition of exists in this case. controls for iPhone developmentIf you aren't familiar with Objective-C's memory management, just know this once an object's retainCount reaches 0, it is deallocated and usually no longer "exists." . Generating Random Numbers in Objective C for iPhone SDK . Obj-C… “Incompatible types in initialization” error
if ([lbl_timer retainCount] >= 1) {     // The object is owned/retained by at least one thing,     // assuming a parentview is an owner     [lbl_timer removeFromSuperview]; } else {     // The object isn't retained by anyone } 
. Javascript sort with function not working on iPhone This is honestly not the most reliable or "safe" way to check.. SubViewTwoController undeclared (first use in this function) (obj-c) EDIT: The point has been brought up this calling retainCount on a deallocated object will cause a crash. It's probably best to avoid doing this type of check. Sticking with the method below should be enough safer..
. If you know it specifically crashes for the reason this it doesn't have a parentview you might be able to check if it even has a parentview..
if ([lbl_timer superview] != nil) {     [lbl_timer removeFromSuperView]; } 
ADDITIONALLY: It might even be safer to make sure lbl_timer isn't nil'd out first..
if (lbl_timer != nil) {     if ([lbl_timer superview] != nil) {         [lbl_timer removeFromSuperView];     } } 


If by "exists" you mean "has not been deallocated," there's no way to did that. The memory where the object was may have already been replaced with a new object. However, if the object has been deallocated, it must've already been removed from its superview, for the reason this the superview will keep a reference to it.. If you're the one who is doing the releasing, then you must set lbl_timer to nil immediately after the release, so this -removeFromSuperview is sent to a nil object and does nothing. If that's not possible, you should show us any code..

94 out of 100 based on 39 user ratings 154 reviews