1. Home
  2. Computing & Technology
  3. Delphi Programming

Freeing Objects in Delphi's TStrings Items
Generic FreeObjects for TStrings

By Zarko Gajic, About.com Guide

The TListBox or TComboBox expose the Items property, of type TStringList, where each string item can be associated with an object.

The TStringList class implements the abstract properties and methods introduced by TStrings.

The TStrings object does not own the objects you add this way. Objects added to the TStrings object still exist even if the TStrings instance is destroyed. Objects must be explicitly destroyed by the application / developer - you. If not, your application will leak memory.

Here are a few examples of storing objects along with strings in a TStringList.

Generic "FreeObjects" for TStrings Descendants

Here's a generic solution to freeing the memory used by objects stored along strings in a TStrings descendant.
procedure FreeObjects(const strings: TStrings) ;
var
  idx : integer;
begin
  for idx := 0 to Pred(strings.Count) do
  begin
    strings.Objects[idx].Free;
    strings.Objects[idx] := nil;
  end;
end;
Usage examples:
FreeObjects(ComboBox1.Items);

FreeObjects(ListBox1.Items);
Note: if objects were not added to items, nothing bad with happen if you call the FreeObjects procedure.

Note: Delphi 2009 (and later versions) implementation of the TStringList class exposes the OwnsObjects property. When OwnsObjects is true, objects associated with strings will be freed by the TStringList when items/strings are removed (deleted) from the list.

Delphi tips navigator:
» Changing the Title of a Print Dialog in Delphi - Specifing TPrintDialog's Caption
« Disconnect a Network Drive from Delphi - Programmatically Remove a Network Connection

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2009 Tips
  7. Generic Solution to Freeing Objects in Delphi's TStringList Collections

©2009 About.com, a part of The New York Times Company.

All rights reserved.