I'm new to Delphi and trying to figure out how to deal with memory management. I have a class, TFileData, that is dynamically allocated and put into a list. Every time I reload data from files I need to release the old objects and allocate new.
To allocate I use this function:
function TImportXmlForm.GetLanguageFileData: TList<TFileData>;
begin
if FAllFiles = nil then
FAllFiles := TList<TFileData>.Create;
Result := FAllFiles;
end{function};
To deallocate:
if Assigned(FAllFiles) then
begin
while FAllFiles.Count > 0 do
begin
FAllFiles.Items[0].Free;
FAllFiles.Delete(0);
end;
FAllFiles.Free;
FAllFiles := nil;
end{if};
What is the "best practice" for this kind of programming patterns?
Use TObjectList<T>
instead of TList<T>
.
By default TObjectList<T>
will free the object when you delete it from the list or all objects when you free the objectlist itself. This is controlled by the OwnsObjects
parameter of the constructor which is by default True
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With