我在程序中创建了一个备忘录,使用以下代码:
Global_MemoIni := TMemo.Create(Conf);
Global_MemoIni.Parent := Conf;
Global_MemoIni.Visible := False;
Global_MemoIni.Align := alClient;
Global_MemoIni.WordWrap := False;
当我再次调用该过程时,它会再次创建global_memoini 我如何知道组件是否已创建,因此我不需要再次调用它?
更新:我可以使用创建代码上方的Global_MemoIni.Free
,以便下次创建
Global_memoini
一次......但我想知道这是否已创建......
谢谢
答案 0 :(得分:5)
您可以检查Global_MemoIni是否为Nil,如果是,则创建TMemo。否则它已经存在,您可以使用Free
或FreeAndNil
释放它。如果您使用免费,请注意将Nil
分配给Global_MemoIni
。如果不这样做,则无法使用Global_MemoIni <> Nil
检查。
答案 1 :(得分:3)
老实说,我不明白使用备忘录而不是更轻量级的TStringList。只是做
unit UnitName;
interface
uses SysUtils, Windows, Classes, ...;
var Global_INI: TStringList; // <-- it's defined in the interface section, therefore
// it can be accessed by any unit which uses this unit
implementation
initialization
Global_INI := TStringList.Create;
Global_INI.LoadFromFile( 'C:\config.ini' ); // <-- replace the file name with the
// one you want
finalization
FreeAndNil( Global_INI );
end;
答案 2 :(得分:1)
如果您不知道对象使用的创建状态:
if not Assigned(Global_MemoIni) then
begin
Global_MemoIni := TMemo.Create(Conf);
...
end
在销毁对象时不要忘记使用FreeAndNil(Global_MemoIni)
。
答案 3 :(得分:1)
不要这样做是一项任意功能。在FormCreate
甚至构造函数中创建组件,或者使其成为表单的只读属性,并使用惰性实例化,即
if not Assigned(Global_MemoIni) then
begin
Global_MemoIni := TMemo.Create(Self);
// rest of your code
end;
Result := Global_MemoIni;
但为什么它是全球性的?如果您将其作为表单的字段和相应的只读属性,则可以轻松访问它,您可以按上面显示的方式保护它。
FWIW,不是自由组件,让业主(表格)这样做。这样,只要表单存在就可以使用它,并且不会发生令人讨厌的无效指针问题。