Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if an object has been deallocated

I have a situation where occasionally my -tableView: numberOfRowsInSection: method asks for the count of a deallocated NSArray. I'd like to be able to test for this array being deallocated in a way that's safe and doesn't make a call to a zombie.

My code currently looks like:

-(NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
    if (! self.offers){
        return 0;
    }
    return [self.offers count];
}

I just debugger-stepped through this and observed it passing the ! self.offers test and then crashing brutally on [self.offers count]. I have NSZombies turned on, and at that line I get the NSLog message:

-[__NSArrayM count]: message sent to deallocated instance 0x283dc0

So whatever self.offers is, at this point, is not nil, but is also not pointed at anything valid. How do I test for that?

EDIT: Thanks for the tough-love, friends. I've figured out why I've been having trouble with my memory management--it's actually been an issue of delegate relationships lingering longer than they were useful. See here for the full answer to my problem: Managing calls to objects that get deallocated when the view is backed out of

like image 269
Dan Ray Avatar asked Dec 03 '22 12:12

Dan Ray


2 Answers

It's not possible to "test" for this-- once an object is deallocated, it's gone, and the pointer to it is effectively garbage. Doing anything with it is liable to crash.

Sorry to be the bearer of bad news, but the only way to get this to work right is to make sure the memory management around (in this case) offers is correct at all uses-- retain and release correctly at all the points where that instance variable is manipulated, and it will never be non-nil garbage.

You should try running the static analyzer (Build->Build and Analyze) to start with-- this tool can help flag memory management pattern issues without a lot of extra digging on your part.

like image 198
Ben Zotto Avatar answered Dec 23 '22 14:12

Ben Zotto


You should avoid the problem by fixing the code so it does not deallocate the array when you obviously still need it.

like image 45
Gary Avatar answered Dec 23 '22 16:12

Gary