Delphi - Using TEdit.tagObject to point to another

2019-08-16 14:46发布

问题:

I am using a descendant of TEdit and using TagObject to store an object. I'm using Firemonkey.

In short, I am working with another object and want to assign a property of that object to my TMyEdit, so that whenever I load the object, the text gets updated, and when I change the text, the object gets updated.

So I do it like this:

Edit1 : TMyEdit;
MyElement:TMyProperty;
...
Edit1.TagObject:=TMyTextProperty(MyElement);

(The typecast is necessary for other reasons. I mention it just in case it is related).

The code works when MyElement is not nil to start with. If MyElement was nil, MyEdit automatically creates a new instance of TMyTextProperty and assigns it to tagObject.

procedure TMyEdit.MyOnChange(Sender : TObject);
begin
  if tagObject=nil then TagObject:=TMyTextProperty.Create('');
  TMyTextProperty(TagObject).value:=text;
end;

I assume that since tagObject is a pointer and i pointed it to MyElement, then myElement would also be updated. But it isn't.

Edit1.TagObject contains my value, but MyElement is stil nil. I need MyElement to be the newly created object.

What am I doing wrong? How can I make sure that whenever the TagObject gets created, the MyElement points to the new object?

Many thanks