Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 721
Cesar Romero Avatar asked Aug 01 '12 18:08

Cesar Romero


3 Answers

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. :)

like image 159
Mason Wheeler Avatar answered Nov 04 '22 03:11

Mason Wheeler


If you want to know if the component is being destroyed, you should use

function IsBeingDestroyed(AComponent : TComponent) : Boolean;
begin
  Result := csDetroying in AComponent.ComponentState;
end;

If you want to be notified when it is being destroyed, using FreeNotification is the way to go.

For a little more detail on FreeNotification, you can check this post.

like image 2
Ken Bourassa Avatar answered Nov 04 '22 01:11

Ken Bourassa


No you can't. Delphi does not keep special track whether or not something is created/destroyed by a class helper.

like image 2
Jeroen Wiert Pluimers Avatar answered Nov 04 '22 03:11

Jeroen Wiert Pluimers