delphi – Spring4D: Why is list of type TObjectList freed automatically after iteration? – Stack Overflow
Posted by jpluimers on 2019/11/28
A nice question and even nicer answer at [WayBack] delphi – Why is list of type TObjectList freed automatically after iteration? – Stack Overflow.
It comes down to the Spring4D collection classes expecting to be accessed using interface references because they descend from TInterfacedObject
which also favours interface references over object references.
If you access them solely using object references, they start out with a reference count of 0 (zero). If an operation then first increases that to 1 (one), then decreases it back to 0 (zero), the collection instance gets freed.
A few nice tips and (sometimes opposing) opinions from the question/answer thread and the referencing G+ thread [WayBack] What do you think, +Stefan Glienke? ##Spring4D – Agustin Ortu – Google+ make them well worth reading.
Some:
- Instead of
TObjectList<TFuu>.Create
, you should useTCollections.CreateObjectList<TFuu>
.
This way, you only needSpring.Collections
in your uses clause - interface-only usage should be enforced by hiding the classes in the implementation, exposing only interfaces
- The functions of
TCollections
only return interface references and – more importantly – allow for code folding starting with Spring4D 1.2. - Hiding the classes in an implementation part is not possible because then this would break any possibility to inherit from these classes and extend them (as I know people do).
- Never use object references to classes that inherit from
TInterfacedObject
because the reference counting can kick in and destroy your instance anywhere (or manually call_AddRef
/_Release
). - if you want to have classes, then use
System.Generics.Collections
–jeroen
Leave a Reply