I’d like to make a record as an object’s property. The problem is that when I change one of the fields of this record, the object isn’t aware of the change.
type
TMyRecord = record
SomeField: Integer;
end;
TMyObject = class(TObject)
private
FSomeRecord: TMyRecord;
procedure SetSomeRecord(const Value: TMyRecord);
public
property SomeRecord: TMyRecord read FSomeRecord write SetSomeRecord;
end;
And then if I do…
MyObject.SomeRecord.SomeField:= 5;
…will not work.
So how do I make the property setting procedure ‘catch’ when one of the record’s fields is written to? Perhaps some trick in how to declare the record?
More Info
My goal is to avoid having to create a TObject or TPersistent with an OnChange event (such as the TFont or TStringList). I’m more than familiar with using objects for this, but in an attempt to cleanup my code a little, I’m seeing if I can use a Record instead. I just need to make sure my record property setter can be called properly when I set one of the record’s fields.
Consider this line:
This is in fact a compile error:
Your actual code is probably something like this:
What happens here is that you copy the value of the record type to the local variable
MyRecord. You then modify a field of this local copy. That does not modify the record held in MyObject. To do that you need to invoke the property setter.Or switch to using a reference type, i.e. a class, rather than a record.
To summarise, the problem with your current code is that SetSomeRecord is not called and instead you are modifying a copy of the record. And this is because a record is a value type as opposed to being a reference type.