哪里可以释放动态分配的TFrame组件的对象? [英] Where to free dynamically allocated TFrame's components' objects?

查看:116
本文介绍了哪里可以释放动态分配的TFrame组件的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含TFrame的表格. TFrame包含动态填充的ComboBox.每个ComboBox条目都有一个关联的对象.到TFrame的重写析构函数被调用时,ComboBox中的项目已被清除,而没有释放其关联的对象.无论是将ComboBox放在设计器视图中的窗体上,还是在代码中以nil或TFrame作为其所有者动态创建它,都会发生这种情况.我目前使用包含TFormOnDestroy事件来调用包含TFrame的清理过程.

I have a form containing a TFrame. The TFrame contains a ComboBox that is dynamically populated. Each ComboBox entry has an associated object. By the time the overridden destructor for the TFrame is called, the Items in the ComboBox have already been cleared without freeing their associated objects. This happens whether I drop the ComboBox on the form in designer view, or dynamically create it in code with either nil or the TFrame as its owner. I currently use the OnDestroy event of the containing TForm to call a clean-up procedure of the contained TFrame.

是否有更好的方法,不需要TFrame的容器进行显式过程调用?理想情况下,应将动态添加到ComboBox的对象放到哪里?

Is there a better way that would not need an explicit procedure call by the TFrame's container? Where ideally should the objects added dynamically to the ComboBox be freed?

推荐答案

您说在调用TFrame的析构函数时,ComboBox的项目已被清除.事实并非如此,ComboBox项永远不会清除.当ComboBox销毁Items时,它们的计数仅为0.

You say that when the destructor for the TFrame is called, the Items of the ComboBox have already been cleared. That's not the case, ComboBox items are never cleared. When Items is destroyed by the ComboBox, they've got a count of only 0.

当退出应用程序时,VCL破坏了包含框架和ComboBox的表单,操作系统本身也会破坏本机ComboBox控件,因为它被放置在要破坏的窗口中.当您以后访问这些项目以释放​​帧析构函数中的对象时,VCL必须重新创建一个本机ComboBox控件,该项目的计数为0.

When you exit your application and the VCL destroys the form containing the frame and the ComboBox, the native ComboBox control is also destroyed by the OS since it is placed in a window being destroyed. When you later access the items to be able to free your objects in the frame destructor, the VCL have to recreate a native ComboBox control, having an item count of 0.

我建议的解决方案很简单.不要将框架留给框架,而要在窗体的OnDestroy事件中销毁框架.那将在表单的基础窗口被销毁之前,因此您将能够访问您的对象.

The solution I'd propose is easy. Don't leave freeing your frame to the framework, instead, destroy your frame in the OnDestroy event of your form. That would be before the underlying window of the form is destroyed, hence you'll be able to access your objects.

表单单位

procedure TMyForm.FormDestroy(Sender: TObject);
begin
  MyFrame.Free;
end;

框架单位

destructor TMyFrame.Destroy;
var
  i: Integer;
begin
  for i := 0 to ComboBox1.Items.Count - 1 do
    ComboBox1.Items.Objects[i].Free;
  inherited;
end;

这篇关于哪里可以释放动态分配的TFrame组件的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆