We help IT Professionals succeed at work.

TList problem

vbmn
vbmn asked
on
TList problem

How to destroy (free) object and delete it from TList ?

Please, give me an example. Thanks.
Comment
Watch Question

Commented:
Hi vbnm,

VAR
  Cnt : Integer;
Begin
  For cnt := List1.count-1 Downto 0 Do
    TyourObject ( List1.Items[cnt]^).Free
End;

Best Regards

Cesario
Commented:
Well, the question says "destroy (free) object _and_ delete it from list" so (presuming it's a single object we are talking about) I would say

procedure DelAndFree(list:TList;idx:integer);
var obj:TObject;
begin
     obj:=list[idx];
     list.Delete(idx);
     obj.Free;
end;

F.

Author

Commented:
Thanks. I Accept fva's Comment as Answer.
fva

Commented:
Just one more comment: I could have said:

TObject(list[idx]).Free;
list.Delete(idx);

but it happened to me more than once to check for that particular list inclusion in the Destroy of the object and call again the DelAndFree proc (with really bad results).
So I made a habit of taking the object out of the list first and free it afterwards.

Yours,
F.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.