How to use Freeandnil in this case?

Asked

Viewed 85 times

0

I have the following routine that destroys 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;

Note that I need to finish the forms with Freeandnil but I am not able to pass the variable, because there requires a Tobject in case the Unit/Form to be released.

  • Application.components[i].Destroy doesn’t solve?

1 answer

1

If you have nothing programmed in OnClose it is not necessary 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;

It is worth remembering that it is not a good practice to perform this type of treatment. The correct for processing forms 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 not destroyed trusting that in the destruction of the form will clean up, you are mistaken!

  • Yes I do the sequence you gave me, but my application allows you to open several different formulas, so sometimes the user will close in the main form, there already saw right

Browser other questions tagged

You are not signed in. Login or sign up in order to post.