原因是因为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;
或者,删除活动引用并让 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;