2

我在事件中使用以下代码在我的表单上创建了一个元素OnShow

procedure TForm4.FormShow(Sender: TObject);
var
  VertScrollLink:TVertScrollBox;
begin
  VertScrollLink := TVertScrollBox.Create(form4);
  VertScrollLink.Align := TAlignLayout.Client;
  VertScrollLink.Parent := form4;
end;

在某些操作中,我需要动态删除布局:

for LIndex := form4.ComponentCount-1 downto 0 do
begin
  if (form4.Components[LIndex].ToString='TVertScrollBox') then
  begin
    //showmessage(form4.Components[LIndex].ToString);
    form4.Components[LIndex].Free;
  end;
end;

此代码在 Windows 上运行良好,但在 Android 上不会删除任何内容。

4

1 回答 1

6

原因是因为Delphi 在移动平台(iOS 和 Android)上对对象使用自动引用计数,而不是在桌面平台(Windows 和 OSX)上。你Free()实际上是一个空操作,因为从Components[]属性访问组件会增加它的引用计数,然后Free()会减少它(事实上,编译器应该发出关于代码无效的警告)。该组件仍然具有对它的活动引用(它的OwnerParent),因此它实际上并没有被释放。

如果要强制释放组件,则需要调用DisposeOf()它,例如:

for LIndex := form4.ComponentCount-1 downto 0 do
begin
  if form4.Components[LIndex] is TVertScrollBox then
  begin
    form4.Components[LIndex].DisposeOf;
  end;
end;

或者,删除活动引用并让 ARC 正常处理破坏:

var
  VertScrollLink: TVertScrollBox;
  LIndex: Integer;
begin
  ...
  for LIndex := form4.ComponentCount-1 downto 0 do
  begin
    if form4.Components[LIndex] is TVertScrollBox then
    begin
      VertScrollLink := TVertScrollBox(form4.Components[LIndex]);
      VertScrollLink.Parent := nil;
      VertScrollLink.Owner.RemoveComponent(VertScrollLink);
      VertScrollLink := nil;
    end;
  end;
  ...
end;

话虽如此,您可能会考虑跟踪您创建的组件,以便以后无需使用循环来查找它:

type
  TForm4 = class(TForm)
    procedure FormShow(Sender: TObject);
    ...
  private
    VertScrollLink: TVertScrollBox;
    ...
  end;

procedure TForm4.FormShow(Sender: TObject);
begin
  VertScrollLink := TVertScrollBox.Create(Self);
  VertScrollLink.Align := TAlignLayout.Client;
  VertScrollLink.Parent := Self;
end;

begin
  ...
  if Assigned(VertScrollLink) then
  begin
    VertScrollLink.DisposeOf;
    { or:
    VertScrollLink.Parent := nil;
    VertScrollLink.Owner.RemoveComponent(VertScrollLink);
    }
    VertScrollLink := nil;
  end;
  ...
end;
于 2016-08-18T21:54:51.280 回答