I am using Delphi XE2. I am creating a custom TComboBox so that I can easily add key / string pairs and handle cleanup in the component destructor.
All if not (csDesigning in ComponentState) code if not (csDesigning in ComponentState) omitted for brevity.
interface type TKeyRec = class(TObject) Key: string; Value: string; end; TMyComboBox = class(TComboBox) public destructor Destroy; override; procedure AddItemPair(const Key, Value: string); end; implementation destructor TMyComboBox.Destroy; var i: Integer; begin for i := 0 to Self.Items.Count - 1 do Self.Items.Objects[i].Free; Self.Clear; inherited; end; procedure TMyComboBox.AddItemPair(const Key, Value: string); var rec: TKeyRec; begin rec := TKeyRec.Create; rec.Key := Key; rec.Value := Value; Self.Items.AddObject(Value, rec); end;
When the application closes, the destructor is called, but the Items.Count property Items.Count not available because the TComboBox must have a parent control to access this property. By the time the destructor is called, it no longer has a parent control.
I saw this problem before and had to store objects in a separate TList and release them separately. But this only works because the order I added to the TList was always the same as the lines added to the combo box. When the user selected a row, I could use a list index to find the correlating object in the TList . If the combo box is sorted, then the indices will not match, so I cannot always use this solution.
Has anyone else seen this? How did you think about the problem? It would be very nice to be able to free objects in the component destructor!
source share