pyscripter 689 Posted March 16, 2022 (edited) I always thought class vars are supposed to be initialized. See also this Stackoverflow question. However in Alexandria 11.1 I got bitten by this: type TMyComponent = class(TComponent) public class var GlobalInstance: TMyComponent ; constructor Create(AOwner: TComponent); override; end constructor TMyComponent .Create(AOwner: TComponent); begin inherited Create(AOwner); if Assigned(GlobalInstance) then raise Exception.Create('TMyComponent is a singleton. You can only have one!'); GlobalInstance := Self; end; When I added such a component to a data module in the 11.1 IDE an exception was raised. It was working fine with 11.0. Was I making a wrong assumption or is this an Alexandria 11.1 bug? Update: My stupid fault. Actually the error has occurred when I closed one project and opened another one with the same component. I should set the GlobalInstance to nil in the desctructor, which I did not. Even then the above approach is problematic if for instance you have have two projects in the same project group using this component. I think this would create a problem. Any better way of having a singleton component without causing issues in the IDE? Edited March 16, 2022 by pyscripter Share this post Link to post
Lajos Juhász 293 Posted March 16, 2022 5 minutes ago, pyscripter said: When I added such a component to a data module in the 11.1 IDE an exception was raised. It was working fine with 11.0. Was I making a wrong assumption or is this an Alexandria 11.1 bug? It's not documented at https://docwiki.embarcadero.com/RADStudio/Sydney/en/Fields_(Delphi). PS. I am also in a couple of minutes will install Delphi 11.1, hopefully I not going to see any new bugs. Share this post Link to post
FPiette 383 Posted March 16, 2022 Quote Any better way of having a singleton component without causing issues in the IDE? Look at TMessageManager class (System.Messaging unit). They implemented a class var for the default manager and a class property with a getter that initialize the call var if not already done, then return the instance. 1 Share this post Link to post