Search code examples
delphilifecycleclass-helpers

Is there any way to know if a object is being created or destroyed inside a class helper?


I have few class helpers for components to create sub-components, like popup menus, to access this sub-components in run time, I create a Singleton TDictionary.

My question is how do I know that the owner-component is being destroyed to remove the sub-component from the TDictionary?

If it is a specialized component I add it in the destructor, but I cannot add constructor and/or destructor in the class helper.

Edit - Solution

I created a base object that accepts TObject as parameters, when used, the remove action must be done manually.

Then I inherited a new class from it, override the methods to accept only TComponent. This is how the relevant part of the code is now:

type     
  TCustomLinkedComponents = class(TCustomLinkedObjects)
  strict private
    type
      TCollector = class(TComponent)
      protected
        procedure Notification(AComponent: TComponent; Operation: TOperation); override;
      end;
  strict private
    FCollector: TCollector;
[..]
  end;

procedure TCustomLinkedComponents.Add(Owner: TComponent; const LinkedName: string; LinkedComponent: TComponent);
begin
  inherited Add(Owner, LinkedName, LinkedComponent);
  FCollector.FreeNotification(LinkedComponent);
end;

procedure TCustomLinkedComponents.TCollector.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited;
  if Operation = opRemove then
    LinkedObjects.Remove(TObject(AComponent));
end;

Using this approach I can resolve my actual need and let opened to be easily extented latter.


Solution

  • Instead of a TDictionary, make a custom TComponent descendant that contains a TDictionary. Then look into how TComponent.FreeNotification works, and the solution should become obvious. :)