views:

385

answers:

2

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

+1  A: 

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.

John Calsbeek
You should always, always ALWAYS set a value to nil after you are releasing it for the last time. That is mostly in dealloc - make sure you set references to nil.
Kendall Helmstetter Gelner
A: 
Neil Daniels
Thanks for your reply.there was a parent view, but I wanted to know if it has already removed, it was crashing on second removal, I think. I had another global variable changing with it, I used it as a flag, cause it was urgent.I'll look in to the memory management, and the 'nil' was a new idea for me. thanks again
pMan
Not sure if you can invoke `retainCount` for objects already deallocated, especially if the memory was reused.
notnoop
Ah, good point. I'd have to test that out, but ya, that might cause a crash. It probably would be safer to test to make sure the object isn't nil'ed out first.
Neil Daniels
Sending `-retainCount` to an object that has been deallocated is almost guaranteed to crash. About the only time that `-retainCount` will ever return 0 is if it was sent to a nil object.
John Calsbeek