How can i know if the user define component is created?
I create a memo inside a procedure, using this code:
Global_MemoIni := TMemo.Create(Conf);
Global_MemoIni.Parent := Conf;
Global_MemoIni.Visible := False;
Global_MemoIni.Align := alClient;
Global_MemoIni.WordWrap := False;
When I call the procedure again it creates the开发者_开发技巧 global_memoini again.
How can I know if the component is created so I don't need to call it again?Update : Can I use the Global_MemoIni.Free
above the creation code so the next time create
the Global_memoini
once... But i want to know if this is created...
Thank you
You can check if Global_MemoIni is Nil and create the TMemo if it is. Otherwise it already exists, you can then free it using Free
or FreeAndNil
. If you use free be careful that you assign Nil
to Global_MemoIni
. If you don't, you can't use the Global_MemoIni <> Nil
check.
I honestly don't understand the point of using a memo in stead of a TStringList which is more lightweight. just do
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;
Don't do this is an arbitrary function. Either create the component in the FormCreate
or even the constructor of the form, or make it a read-only property of the form, and use lazy instantiation, i.e.
if not Assigned(Global_MemoIni) then
begin
Global_MemoIni := TMemo.Create(Self);
// rest of your code
end;
Result := Global_MemoIni;
But why is it global? If you make it a field and corresponding read-only property of the form, it is easily accessible and you can protect it in the way shown above.
FWIW, instead of Free-ing the component, let the Owner (the form) do that. That way, it is available as long as the form exists, and no nasty invalid pointer issues can take place.
If you do not know the creation state of object use:
if not Assigned(Global_MemoIni) then
begin
Global_MemoIni := TMemo.Create(Conf);
...
end
And don't forget to use FreeAndNil(Global_MemoIni)
when destroying the object.
精彩评论