Querying to an instance if it is already deallocated
I know about memory management rules and there开发者_如何学运维 is no need of what I am asking if I follow these rules. But, I wonder if there is a way to know if an instance is already deallocated without throwing an exception. My app uses an object what any view on my app can become its delegate. Sometimes, I'm getting this well known error. I can avoid this by setting the delegate to nil on the dealloc method of the current delegate owner. In summary... Do I have any way to know if an object is deallocated?
Thanks.
Can I tell if a pointer now points to garbage?
No, not really. Once an object is deallocated, its memory can be reused at any time. Sometimes it'll actually point to garbage (causing a crash), sometimes it'll point to a different Obj-C object, and sometimes the memory will not have been reused yet.
The main exception is that if you set the environment variable NSZombieEnabled=YES
(in "edit scheme" somewhere in Xcode 4), the memory used by objects will never be deallocated (unless you also set NSDeallocateZombies=YES
, or so); instead, sending a message to the zombie will cause an exception. It's useful for debugging, largely because it tells you the class name of the instance that got deallocated.
I usually try to set pointers to nil
once the underlying object is deallocated. In this case, you can simply check whether the pointer is nil
to see if the object has been deallocated. This isn't always possible, but often is.
The answer to your question is unequivocally "no". You can't ask a pointer whether it is valid without risking a crash due to invalid pointer access. The good news is that setting delegate objects to nil is the correct thing to do, so what you're currently doing is good.
精彩评论