In Delphi, why does the Assigned() function still return True after I call the destructor?
The below example code will write \"sl is still assigned\" to the console.
We have simple rules:
If you want to use Assigned() to check if an object Obj is already created or not,
then make sure you use FreeAndNil(Obj) to free it.
Assigned() only says if an address is assigned or not.
The local object reference is always assigned a garbage address (some random address), so it is good to set it to nil before using it.
Example: (This is not the full code)
{Opened a new VCL application, placed a Button1, Memo1 on the form
Next added a public reference GlobalButton of type TButton
Next in OnClick handler of Button1 added a variable LocalButton
Next in body, check if GlobalButton and LocalButton are assigned}
TForm2 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
GlobalButton: TButton;
end;
procedure TForm2.Button1Click(Sender: TObject);
var
LocalButton: TButton;
begin
if Assigned(GlobalButton) then
Memo1.Lines.Add('GlobalButton assigned');
if Assigned(LocalButton) then
Memo1.Lines.Add('LocalButton assigned');
end;