0
votes

I often use extenders of TList: TList<SomeClass1>, TList<SomeClass2> etc.

Almost every time there's a need to empty them, deleting all the objects they store.

I do it by writing a specific procedure for every specific TList. For example:

while Dirs.Count > 0 do
begin
    Dirs.Items[0].Free;
    Dirs.Delete(0);
end;

Is there a way to code a universal procedure? Something like this:

procedure EmptyAList(_List : TClass; _Object : TClass);
begin
     _Object(_List.Items[0]).Free;
     _List.Delete(0);
end;

Or anything of the kind.

1

1 Answers

7
votes

Use TObjectList<T> instead of TList<T>. TObjectList<T> is a TList<T> descendant that owns and destroys stored objects by default.

All you have to do is make sure its OwnsObjects property is true (it is by default), and then you can call its Clear() method to automatically free all of the containing objects. For example:

Dirs: TObjectList<SomeClass>;
...
Dirs.Add(SomeObject);
...
Dirs.Clear;

TObjectList<T> documentation