I was wrong about the life-cycle of a Form. I thought it was Free()'d from Application.Run, but it's not. This appears to be the reality...

I was wrong about the life-cycle of a Form. I thought it was Free()'d from Application.Run, but it's not. This appears to be the reality...

FormDestroy() is a called, but not where I thought. 

The form is being created in the *.dpr with a CreateForm() and the associated FormDestroy() connected to the form isn't called until the "end." in the *.dpr, when a "unit finalization" calls Vcl.Forms.DoneApplication -> 
System.Classes.TComponent.DestroyComponents -> 
INstance.Destroy() ... and only then is FormDestroy() executed.

var
   MyApp      : TApplication;

begin
.
.
.
   MyApp := Application;
   MyApp.Initialize();
   MyApp.CreateForm(TFMyForm, FMyForm);
   MyApp.Run();
.
.
.
end. -> finally calls 
1) Vcl.Forms.DoneApplication -> which calls
2) System.Classes.TComponent.DestroyComponents -> which calls
3) Instance.Destroy() -> which calls
4) FormDestroy()

Comments

  1. VCL: A TForm is a TComponent. A TComponent is freed by its Owner. If you set Owner to NIL this behavior is disabled and you have to manage the lifecycle yourself. You can set Owner via constructor parameter and/or the Owner property.
    FM: I think its the same.. but have not looked into that.

    ReplyDelete
  2. Barry Staes thanks. Yeah. I guess that's part of why I got confused. I must have looked at TForm.Create() 3x thinking that I forgot a call to "inherited" (which isn't needed), as I thought the ownership had been lost or I made a mistake that it was trashed. Turns out, I was just wrong about when the FormDestroy() method is called for the form.. which resulted in a lot of searching on a incorrect assumption.

    ReplyDelete
  3. Cristian PeÈ›a essentially, that's what I did.. in order to control when the FormDestroy() was called (instead of waiting for finalization)...

    begin
    ..
    ..
       MyApp := Application;
       MyApp.Initialize();
       MyApp.CreateForm(TFMyForm, FMyForm);
    try
       MyApp.Run();
    finally
       FMyForm.Free();
    end;
    ..
    ..
    end.

    ReplyDelete

Post a Comment