delphirttidelphi-10.3-rio

Delphi RTTI Property on memory


After iterating my list of properties in the class using RTTI, I save it in a variable FMap: TDictionary<TRttiProperty, TMappedField>, and I also save a variable FPropertyPK: TRttiProperty - I use it to map database fields. After that, I access this TDictionary and this variable smoothly in my CRUD functions, everything works perfectly in 4 projects where I use this class.

However, I created a new project (those others were not initiated by me), and simply after iterating, creating, and adding everything to the TDictionary, in the next function I call, I have memory errors related to the properties in it, everything comes as nil. But only specifically in this project, with the same screen and same function working in the other projects.

I've compared the project compilation options, one by one, and made everything the same in this new project, but it doesn't work. In this project, Delphi destroys my memory reference for everything related to RTTI.

Any solutions?


Solution

  • The RTTI instances are owned by the TRTTIContext instance. To keep these instances alive you need to keep the context alive.

    TRttiContext provides two class methods for that: KeepContext and DropContext.

    So you need to call TRttiContext.KeepContext before adding those instances to your dictionary and call TRttiContext.DropContext when the dictionary is destroyed.

    Also make sure that the dictionary doesn't take ownership over those instances.