Reputation: 387
I'm trying to add a TDateTime
value into a TStringList
object using Delphi 10.4 Sydney.
I managed to do it like this:
TDateTimeObj = class(TObject)
strict private
DT: TDateTime;
protected
public
constructor Create(FDateTime: TDateTime);
property DateTime: TDateTime read DT write DT;
end;
constructor TDateTimeObj.Create(FDateTime: TDateTime);
begin
Self.DT := FDateTime;
end;
Then I add it to the TStringList
like this:
procedure TForm1.Button1Click(Sender: TObject);
var
b: TStringList;
begin
b := TStringList.Create;
b.AddObject('a', TDateTimeObj.Create(now));
b.AddObject('b', TDateTimeObj.Create(now));
FreeAndNil(b);
end;
It works, but when I close the program I have a memory leak as I did not free the TDateTimeObj
objects.
Is there a way to free the objects automatically, or a better way to achieve the same result?
Upvotes: 1
Views: 385
Reputation: 12292
You have to make the string list own the added objects. Owned objects are destroyed when the string list is destroyed.
procedure TForm1.Button1Click(Sender: TObject);
var b: TStringList;
begin
b := TStringList.Create(TRUE); // TRUE means OwnObjects
try
b.AddObject('a', TDateTimeObj.Create(now));
b.AddObject('b', TDateTimeObj.Create(now));
finally
FreeAndNil(b); // Owned objects will be destroyed as well
end;
end;
Upvotes: 5