40media 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?


for- loop in background thread accesses each index more than once — iPhone dev


Update coordinate property of MKAnnotation on parent viewcontroller after Touch End event?
You'll really need to clarify in what sense you mean by "exists" as that can be interpreted in various ways..
Memory Management Question in Objective C
You may find that an object's retainCount may satisfy your definition of exists in this case.

UITableView frame height animation glitch
If you aren't familiar with Objective-C's memory management, just know that once an object's retainCount reaches 0, it is deallocated and usually no longer "exists."
Should a property list be managed by its own model object?
How to remove NSString Related Memory Leaks?
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 } 
XCode, iPhone, WebKit Framework - What am I missing?
This is honestly not the most reliable or "safe" way to check..
What describes NSNumberFormatter -maximumSignificantDigits?
EDIT: The point has been brought up that calling retainCount on a deallocated object will cause a crash.

It's probably best to avoid doing that type of check.

Sticking with the method below should be much safer..
. If you know it specifically crashes because 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 do 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, because the superview will keep a reference to it.. If you're the one who is doing the releasing, then you can set lbl_timer to nil immediately after the release, so that -removeFromSuperview is sent to a nil object and does nothing.

If that's not possible, you should show us some code..

64 out of 100 based on 59 user ratings 684 reviews