Mega Code Archive

 
Categories / Delphi / Ide Indy
 

Generic Solution to Freeing Objects in Delphis TStringList Collections

Title: Generic Solution to Freeing Objects in Delphi's TStringList Collections 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.