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.
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. :)
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.
No you can't. Delphi does not keep special track whether or not something is created/destroyed by a class helper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With