avizzini
avizzini

Reputation: 789

Objective-C [on OS X Leopard] Garbage Collection, nil Question

I have a question about garbage collection in Objective-C

If I have an object, lets call it 'A'. And 'A' contains instance variables that point to other multiple objects. If I set the pointer to A equaled to nil, will the garbage collector understand that all that is contained in 'A' is also now unused and handle the cleanup? Or do I need to also explicitly make all instance variables in 'A' nil for memory cleanup to occur?

Upvotes: 3

Views: 211

Answers (2)

Anonymous
Anonymous

Reputation: 89

Yes, absolutely, it will work.

HOWEVER, note that garbage collection is non-deterministic, that is, there's no telling when it will run.

Therefore, any destructors you need called won't be called immediately when you nil the pointer.

If the object 'A' is, or holds references to, file objects, database objects, connection objects, etc. then you will need to use reference counting to ensure that these are freed immediately.

Otherwise, use GC; it's a lot less painful.

Upvotes: 1

bbum
bbum

Reputation: 162712

Yes, it just works; the collector knows that a sub-graph of objects, potentially complexly inter-connected, that no longer has any connections from the live objects is garbage.

The collector does full cycle detection, too.

Upvotes: 4

Related Questions