Hello. I try to release objects associated with TCombobox like this

Hello. I try to release objects associated with TCombobox like this

procedure FreeObjectsInCombobox(ACombobox: TComboBox);
var i: Integer;
obj: TObject;
begin
for I := 0 to (ACombobox.Items.Count - 1) do
begin
obj := ACombobox.Items.Objects[i];
if Assigned(obj) then
begin
FreeAndNil(Obj);
ACombobox.Items.Objects[i] := nil;
end;
end;
end;

There are objects of different types in Combobox, but all of them inherited from TObject

But if object is already released condition "Assigned(obj)" still passing fine and there is access violation on "FreeAndNil(obj)"

Can anybody give me advice how to properly release objects or check if it is already released?

Comments

  1. My suggestion:

    procedure FreeObjectsInCombobox(ACombobox: TComboBox);
    var i: Integer;
    obj: TObject;
    begin
    ACombobox.Items.beginupdate;
    for I := 0 to (ACombobox.Items.Count - 1) do
    begin
    obj := ACombobox.Items.Objects[i];
    if Assigned(obj) then
    begin

    ACombobox.Items.Objects[i] := nil;
    Objet. Free:;
    end;
    end;
    ACombobox.Items.endupdate;
    end;

    ReplyDelete
  2. Attila Kovacs I tend to think there is a life cycle outside of the combobox.

    ReplyDelete
  3. Thx for advices. This is legacy project that I need to refactor.

    ReplyDelete

Post a Comment