osi
osi

Reputation: 207

Why is the Obj-C GC clearing my reference?

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?

Upvotes: 0

Views: 359

Answers (2)

robottobor
robottobor

Reputation: 11772

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.

Upvotes: 1

user57368
user57368

Reputation: 5765

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.

Upvotes: 1

Related Questions