Question

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?

thanks

Was it helpful?

Solution

You'll really need to clarify in what sense you mean by "exists" as that can be interpreted in various ways.

You may find that an object's retainCount may satisfy your definition of exists in this case. 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."

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
}

This is honestly not the most reliable or "safe" way to check.

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];
    }
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top