Thema: Delphi Free Objects in List

Einzelnen Beitrag anzeigen

Delphi-Lover

Registriert seit: 19. Okt 2004
Ort: Amsterdam
30 Beiträge
 
Delphi 2005 Professional
 
#1

Free Objects in List

  Alt 18. Apr 2007, 15:05
Hello,

I just want to be sure about a thing I wonder about.
Normally to free objects added to a list I do the following:

Delphi-Quellcode:
//The object I add to the List
TMyListObject = Class(TObject)
        ID : Integer;
        Name : String;
End;

//The List
MyList : TStringlist;

//Add the Object in the list
Var aMyListObject : TMyListObject;

aMyListObject:=TMyListObject.Create;
aMyListObject.ID=1;
aMyListObject.Name='Example';

MyList.AddObject('1',aMyListObject);
Normally When I want to free the objects in the list I cast the ListObject in the Free Like:

Delphi-Quellcode:
Var Index : Integer;
Begin
  For Index:=0 to MyList.Count-1 do
  Begin
    TMyListObject(MyList.Objects[Index]).Free;
  End;
  MyList.Clear;
End;
Now I hear that casting is not needed and you can do it directly by the list.objects.free like:

Delphi-Quellcode:
var Index : Integer;
Begin
  for Index := 0 to MyList.Count - 1 do
  begin
    if Assigned(MyList.Objects[Index]) then
    begin
      MyList.Objects[Index].Free;
      MyList.Objects[Index]:=nil;
    end;
  end;
End;
Note, there is no destructor in the ListObject.
I thought you have to cast the listobject while freeing the List, but maybe this is not needed.

Thanks !

Delphi-Lover
Rob
  Mit Zitat antworten Zitat