delphidelphi-xe4

Free Object's Field By Rtti


How can I Free Fields of my object by Rtti in delphi (XE4)?

I need to free all fields dynamically

I can find fields but i don't now how i should free them:

destructor TKnBase.Destroy;
var
  AContext: TRttiContext;
  AField: TRttiField;
begin
  for AField in AContext.GetType(Self.ClassInfo).GetFields do
  begin
     -->free filed (AField)
  end;

  inherited;
end;

I try with this but doesn't work:

destructor TKnBase.Destroy;
type
  dp = ^TObject;
var
  AContext: TRttiContext;
  AField: TRttiField;
  p: dp;
begin
  for AField in AContext.GetType(Self.ClassInfo).GetFields do
  begin
    p := dp(NativeInt(AField) + AField.Offset);
    TObject(p^).Free;
  end;

  inherited;
end;

Solution

  • The offset is relative to the instance pointer. Your code should be:

     p := dp(NativeInt(Self) + AField.Offset);
    

    You might prefer to use the field object's GetValue method to read the field's value. And so avoid all that pointer arithmetic.

    What you are doing here is very limiting. All derived classes are forced to fit this policy. All fields must be objects and must be owned by this class. You can't have integer fields, boolean fields and so on. At the very least you should only attempt to destroy field that are objects.

    My instincts tell me that what you are attempting will prove to be unworkable.