The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,781 other followers

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 use TCollections.CreateObjectList<TFuu>.
    This way, you only need Spring.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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: