Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my TStrings object being destroyed before my destructor has a chance to run?

Tags:

delphi

I have a an object that extends from TFrame. This contains a TCombobox.

I want to make sure i free any associated objects when my frame is destroyed. However when my destructor gets run i can access the combobox, but it's items have been wiped out.

What would do this? How can i access the items in the destructor?

my destructor looks like this;

destructor TfraImportAttachments.Destroy;
begin

  MessageDlg(IntToStr(cboCategory.Items.count), mtInformation, [mbOK], 0);
  FreeObjects(cboCategory.Items);

  inherited;
end;
like image 530
srayner Avatar asked Dec 14 '12 15:12

srayner


1 Answers

A DestroyHandle may have reached the combobox before the destructor. Then the Items are gone because they are not saved to the TCustomComboBox.FSavedItems list in TCustomComboBox.DestroyWnd.

The combobox Delphi object still exists, but the actual control (the one that is accessed through the window handle) is gone. By accessing ComboBox.Items the VCL recreates the actual control so it can retrieve the items, but that new control doesn't have any items, so Items.Count returns 0.

A solution would be to put the items into the combobox and a TObjectList, TList or TList<TObject> depending on what you want to do with them. So the ownership is in the "code" list while the items are still referenced in the combobox.

like image 145
Andreas Hausladen Avatar answered Oct 18 '22 09:10

Andreas Hausladen