pei*_* F. 2 delphi firemonkey delphi-xe7 delphi-10-seattle delphi-10.1-berlin
我在表单上使用此代码在OnShow事件中创建了一个元素:
procedure TForm4.FormShow(Sender: TObject);
var
VertScrollLink:TVertScrollBox;
begin
VertScrollLink := TVertScrollBox.Create(form4);
VertScrollLink.Align := TAlignLayout.Client;
VertScrollLink.Parent := form4;
end;
Run Code Online (Sandbox Code Playgroud)
在某些操作上,我需要动态删除布局:
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;
Run Code Online (Sandbox Code Playgroud)
此代码在Windows上运行良好,但不会删除Android上的任何内容.
原因是Delphi在移动平台(iOS和Android)上使用对象自动引用计数,但在桌面平台(Windows和OSX)上不使用.你Free()实际上是一个无操作,因为从Components[]属性访问组件将增加其引用计数,然后Free()将减少它(事实上,编译器应该发出关于代码无效的警告).该组件仍然具有对它的活动引用(它的Owner和Parent),因此它实际上没有被释放.
如果要强制释放组件,则需要调用DisposeOf()它,例如:
for LIndex := form4.ComponentCount-1 downto 0 do
begin
if form4.Components[LIndex] is TVertScrollBox then
begin
form4.Components[LIndex].DisposeOf;
end;
end;
Run Code Online (Sandbox Code Playgroud)
或者,删除活动引用并让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;
Run Code Online (Sandbox Code Playgroud)
话虽这么说,您可以考虑跟踪您创建的组件,这样您以后就不需要使用循环来查找它:
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;
Run Code Online (Sandbox Code Playgroud)
begin
...
if Assigned(VertScrollLink) then
begin
VertScrollLink.DisposeOf;
{ or:
VertScrollLink.Parent := nil;
VertScrollLink.Owner.RemoveComponent(VertScrollLink);
}
VertScrollLink := nil;
end;
...
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
695 次 |
| 最近记录: |