views:

169

answers:

2

I am writing an Objective-C program that utilizes the garbage collector.

I am getting *EXC_BAD_ACCESS* in some situations, the classic example of an object being "over freed". Using some of the debugging tips in this technote, namely MallocScribble and *AUTO_LOG_COLLECTIONS*, I can see that my object is being GC'd out from under me.

With that said, here is my code.

I have an NSMutableDictionary that holds the ONLY reference to an object. In a method, I am then doing:

NSObject *object = [dictionary objectForKey:key];

NSLog(@"Object is %@", object);
[dictionary removeObjectForKey:key];

If I remove the object from the dictionary before the NSLog statement, if the GC runs at the right moment, I get the *EXC_BAD_ACCESS*. Removing from the dictionary after never fails.

Why is this?

+1  A: 

The Garbage Collection Programming Guide section on interior pointers seems to be the closest documentation for this phenomenon, but it doesn't seem to quite fit. Try to verify that your app is actually using garbage collection instead of manual reference counting. If the garbage collector is really enabled, then it would seem that it either has a bug or an insufficiently-documented feature.

GC is on, i will be investigating to see if its a GC-related bug. Thanks for the link to that guide!
osi
+1  A: 

Have you verified that the garbage collection is truly on? You could try putting in a -dealloc method in your class and see if you ever hit it. It will never hit with GC on. According to Apple docs the GC should not collect objects pointed to by stack variables so what you're seeing should not happen.

robottobor
Yes, the garbage collector is enabled. Setting the AUTO_LOG_COLLECTIONS environment variable to YES shows that there is a GC right before the error.
osi