开发者

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

开发者 https://www.devze.com 2023-02-18 01:56 出处:网络
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

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 t开发者_StackOverflow社区o also explicitly make all instance variables in 'A' nil for memory cleanup to occur?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消