请参阅对象实例并将其释放

时间:2013-05-10 16:15:16

标签: delphi delphi-xe2

如果我使用此例程创建多个TButton对象:

procedure CreateButton;
begin
  Btn := TButton.Create(nil);
end;

然后,我如何引用特定的对象实例以使用另一种方法释放它:

procedure FreeButton;
begin
  Btn[0].Free;  //???
end;

当然,这不会编译,但我认为问题很明确:我如何声明Btn?我如何释放多个实例?

1 个答案:

答案 0 :(得分:1)

在任何不属于表单(您的代码所做的)的任何地方创建TButton没有多大意义。

话虽如此,为了稍后引用它来释放它,你需要在某处存储对它的引用。

由于您在删除例程中引用“多个按钮”并使用数组代码,我认为您可能想要跟踪一系列按钮。以下是这样做的一个例子:

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);   // Add via Object Inspector Events tab
  private
    { Private declarations }
    // Add these yourself
    BtnArray: array of TButton;
    procedure CreateButtons(const NumBtns: Integer); 
    procedure DeleteBtn(BtnToDel: TButton);
    procedure BtnClicked(Sender: TObject);  
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.DeleteBtn(BtnToDel: TButton);
var
  i: Integer;
begin
  // Check each button in the array to see if it's BtnToDel. If so,
  // remove it and set the array entry to nil so it can't be deleted
  // again.
  for i := Low(BtnArray) to High(BtnArray) do
  begin
    if BtnArray[i] = BtnToDel then
    begin
      FreeAndNil(BtnArray[i]);
      Break;
    end;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  // Create 10 buttons on the form
  CreateButtons(10);
end;

// Called when each button is clicked. Assigned in CreateButtons() below    
procedure TForm1.BtnClicked(Sender: TObject);
begin
  // Delete the button clicked
  if (Sender is TButton) then
    DeleteBtn(TButton(Sender));
end;

procedure TForm1.CreateButtons(const NumBtns: Integer);
var
  i: Integer;
begin
  // Allocate storage for the indicated number of buttons
  SetLength(BtnArray, NumBtns);

  // For each available array item
  for i := Low(BtnArray) to High(BtnArray) do
  begin
    BtnArray[i] := TButton.Create(nil);              // Create a button
    BtnArray[i].Parent := Self;                      // Tell it where to display
    BtnArray[i].Top := i * (BtnArray[i].Height + 2); // Set the top edge so they show
    BtnArray[i].Name := Format('BtnArray%d', [i]);   // Give it a name (not needed)
    BtnArray[i].Caption := Format('Btn %d', [i]);    // Set a caption for it
    BtnArray[i].OnClick := BtnClicked;               // Assign the OnClick event
  end;
end;

如果您将此代码放在新的空白VCL表单应用程序中并运行它,您将在表单上看到10个按钮('Btn 0 through Btn 9`)。单击按钮将从表单(和数组)中删除它。