How to identify Delphi StringList object is created or not
-
06-02-2021 - |
Question
I have declared variable of TStringList in private section. In a button click event I want to access that TStringList object.
sVariable:= TStringList.Create;
sVariable.add('Test1');
Now whenever i click on that button each time its newly created and memory is allocated to that variable. Is there any property/function using which we can determine object is created for that variable or not and it will not give the access violation error also?
La solution
if not Assigned(sVariable) then
sVariable:= TStringList.Create;
sVariable.add('Test1');
Autres conseils
Another way to approach it, expanding on David's answer, is through a property with a read method.
TMyForm = class (TForm)
private
FStrList : TStringList;
public
property StrList : TStringList read GetStrList;
destructor Destroy; override;
end;
implementation
function TMyForm.GetStrList : TStringList;
begin
if not Assigned(FStrList) then
FStrList := TStringList.Create;
Result := FStrList;
end;
destructor TMyForm.Destroy;
begin
FStrList.Free;
inherited;
end;
Edit: Added the Free call in an overridden destructor.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow