How to use FreeAndNil in this case?

0

I have the following routine that destroys the forgotten forms opened by the user:

...    
        for i := qtd - 1 downto 0 do
        begin
                if (Application.components[i] is TForm) then
                begin
                    TForm(Application.components[i]).Close;
                    *** AQUI A NECESSIDADE DO *** 
                    FreeAndNil(Application.components[i]);
                end;
        end;

Please note that I need to end the forms with FreeAndNil but I am not able to pass that variable, since it requires a TObject in case the Unit / Form to be released.

    
asked by anonymous 21.02.2018 / 15:33

1 answer

1

If you do not have anything programmed in OnClose you do not need to trigger it, for this case of course.

    for i := qtd - 1 downto 0 do
    begin
      if (Application.components[i] is TForm) then
      begin
        {Você testou se ele é um TForm, e a resposta foi positiva, então 
         teste qualquer um dos métodos a seguir}  

        TForm(Application.components[i]).Free;
        TForm(Application.components[i]).DisposeOf;
        TForm(Application.components[i]).Destroy; {citado corretamente pelo @Roberto de Campos}
        FreeAndNil(TForm(Application.components[i]));
      end;
    end;

Remember that it is not good practice to perform this type of treatment. The correct one for forms handling would be:

1 - Cria o Formulário
2 - Exibe ele
3 - Destrói ele

Delphi is horrible in memory management, if you have allocated something and have not destroyed relying on the destruction of the form will clean up, be fooled!

    
21.02.2018 / 16:01