创建TMenuItem运行时时,如下所示:
mi:= TMenuItem.Create([owner]);
并添加到TPopupMenu,如下所示:
PopupMenu1.Items.Add(MI);
我是否需要将[owner]指定为PopupMenu1,还是可以使用nil?
在这种情况下,PopupMenu1会免费获得mi,如果是这样,我该如何验证呢?
解决方法
您可以将nil指定为所有者,父项将释放其自己的项.
至于验证,最简单的方法是查看TMenuItem.Destroy中的代码:
destructor TMenuItem.Destroy; begin .. while Count > 0 do Items[0].Free; .. end;
如果这还不够,要查看它的实际运行情况,您可以使用通知机制:
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;