Reputation: 5634
It seems completely irrelevant to require a TComponent as an owner to instantiate an object of some kind. Why are there so many Delphi components that require this?
For example, TXMLDocument requires a TComponent object to instantiate.
Why is this and if there's a good reason, what should I be using in there to "do the right thing"?
Upvotes: 15
Views: 6967
Reputation: 596592
An Owner parameter is only needed for TComponent
descendants, as it is a parameter of the TComponent
constructor. All components that are accessible at design-time for dropping on TForm
, TFrame
, and TDataModule
classes are TComponent
descendants (which includes TXMLDocument
).
Upvotes: 0
Reputation: 2018
You shoudl use this for two reasons: - the ownership mechanism stands also as a kind of garbage collecting system - the ownership mechanism is important in Delphi serialization process (Stream.ReadComponent/WriteComponent etc).
Upvotes: 0
Reputation: 454
The owner component is supposed to manage all its owned components. The owned components gets destroyed automatically when the owner is destroyed.
This helps the developer who just drags components from the tool-palette, drops them on the form and just hooks up the events to get his work done without worrying about managing the lifetime of the components.
The form is the owner of all components dropped on it. The Application object is owner of the form. When the app is closed the Application object is destroyed which in turn destroys the forms and all the components.
But the owner is not really necessary when a components is created. If you pass Nil to the parameter, the component will be created without an owner and in this case it will be your responsibility to manage the component's lifetime.
Upvotes: 38
Reputation: 4027
All TComponent descendents require Owner, it is defined in TComponent constructor. The Owner component is responsible to destroy all the Owned components.
if you want to control the life time, you can pass nil as parameter.
Upvotes: 9
Reputation: 646
There is also something else to be aware of. I have used more than a couple of third party components which rely on an Owner component being passed in the Constructor Create, and if you pass in Nil will throw an exception/AV.
The net result is that these components will work fine when you use the visually within the IDE but cause problems when they are created at run-time.
The cause of these problems is, in a sense, bad design. Nothing in the rules state you cannot/should not pass in NIL as the aOwner parameter.
Upvotes: 3
Reputation: 53366
Just to add some extra information.
Each control also has a parent. (A TWinControl). Where the owner takes care of the lifetime, the parent takes care of showing the object.
For example a form has a panel and the panel has a button. In that case, the form owns the panel and the button. But the form is the parent of the panel and the panel is the parent of the button.
Upvotes: 3