Is it me or is this method useless?
It is not useless to
TComponent itself, it is actually VERY important. But outside of
TComponent, it is useless and should not be used in your own code.
This code is part of the DFM streaming system. It is used to link components created at design-time to the pointers that are declared for them in the owning
TForm/
TDataModule/
TFrame at runtime. For example, if you place a
TButton component named
Button1 on a
TForm at design-time, a variable named
Button1 is declared in the
TForm class, eg:
type
TMyForm = class(TForm)
Button1: TButton; // <--
...
end;
When the DFM is streamed into the Form at runtime, and that
TButton object is created, its
Name property gets set to
'Button1', which then calls
SetReference(True) to set
TMyForm.Button1 to
Self. When that object is later renamed (and during its destruction, it is renamed to
''), setting its
Name to a new value will call
SetReference(False) to set
TMyForm.Button1 to
nil.
I mean, all it does is set the local variable Field to Nil or Self. Am I missing something?
Yes. The code is not setting the local variable itself, it is setting the variable that is being pointing at. Calling
FieldAddress() returns a pointer to a data member, in this case a pointer variable, and then the code sets that pointed-at variable to
nil or
Self as needed.
For example,
MyForm.FieldAddress('Button1') returns
Field := @MyForm.Button1, and then
Field^ := Self/nil is effectively doing
MyForm.Button1 := Self/nil.
Like I said, I'm trying to provide a descendant of TGridColumnTitle a name and I wanted to implement the appropriate checks, which is why I ended here.
This kind of code does not belong in a user-defined
Name property, unless you are manually tracking your own runtime pointers by name, which there are better ways to handle that (
TDictionary, etc).