Creating and Freeing a TMenuItem used by a TPopupMenu
Asked Answered
P

1

7

When creating a TMenuItem runtime as shown below:

mi := TMenuItem.Create([owner]);

and adding to a TPopupMenu like so:

PopupMenu1.Items.Add(mi);

Do I need to specify the [owner] as PopupMenu1 or can I use nil?

Will mi be free by PopupMenu1 in that case, and if so how can I verify it?

Patch answered 16/5, 2012 at 11:33 Comment(0)
J
11

You can specify nil as owner, the parent item will free its own items.

As for verifying, the easiest is to see the code in TMenuItem.Destroy:

destructor TMenuItem.Destroy;
begin
  ..
  while Count > 0 do Items[0].Free;  
  ..
end;


If that's not enough, to see it in action you can use the notification mechanism:

type
  TForm1 = class(TForm)
    PopupMenu1: TPopupMenu;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    mi: TMenuItem;
  protected
    procedure Notification(AComponent: TComponent; Operation: TOperation);
      override;
  end;

  ..

procedure TForm1.Button1Click(Sender: TObject);
begin
  mi := TMenuItem.Create(nil);
  mi.FreeNotification(Self);
  PopupMenu1.Items.Add(mi);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  PopupMenu1.Free;
end;

procedure TForm1.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited;
  if (AComponent = mi) and (Operation = opRemove) then
    ShowMessage('mi freed');
end;

Press Button1 to first add the item to the popup menu. Then press Button2 to free the Popup. The item will notify your form when it is being destroyed.

Jewfish answered 16/5, 2012 at 11:44 Comment(4)
Understood. However, Will there be a problem if I do use an owner for example the Form1 itself? Wouldn't the Form1 Free the TMenuItem also - again? (sorry for not mentioning this in the initial question)Patch
@Patch - No, there won't be a problem. After whichever frees the item (form or the parent item), the item will be removed from its parents' items.Jewfish
and if it's still not enough.. ;o) ReportMemoryLeaksOnShutdown := True; in the project sourceHierocracy
@Whiler, D7 does not have ReportMemoryLeaksOnShutdown :/Patch

© 2022 - 2024 — McMap. All rights reserved.