#1 2017-11-16 20:59:34

automacaosamos
Member
Registered: 2015-02-19
Posts: 20

remove TList/ObjectList from memory

type
   TTestVO = class
  private
    fcode    : Integer;
    fname    : String;
    fanswers : String;
    ftotal   : Real;
  published
    property code    : integer read fcode    write fcode;
    property name    : string  read fname    write fname;
    property answers : string  read fanswers write fanswers;
    property total   : real    read ftotal   write ftotal;
  end;

var
  StringJson : RawUTF8;
  ListObj    : TList;
  Itens      : Integer;
  TestVO     : TTestVO;
begin
  StringJson :='[{"code": 1,"name": "Margaret","answers": "yes","total": 10},{"code": 2,"name": "Mirian","answers": "no","total": 20}]';

  ListObj    := JSONToObjectList(TTestVO,StringJson);

  try
    for Itens := 0 to ListObj.Count -1 do
      TestVO := ListObj[Itens];
  finally
    for Itens := 0 to ListObj.Count - 1 do
      TTestVO(ListObj.Items[Itens]).Free;
    FreeAndNil(ListObj);
  end;



I am trying to remove this object from memory and I have the following error:

"Invalid pointer operation."

Offline

#2 2017-11-16 21:37:13

mpv
Member
From: Ukraine
Registered: 2012-03-24
Posts: 1,539
Website

Re: remove TList/ObjectList from memory

By default TObjectList.OwnsObjects is true, so FreeAndNil(ListObj) will destroy all your objects. But you destroy it before, so pointers to your object is incorrect. Just remove this loop

 for Itens := 0 to ListObj.Count - 1 do
      TTestVO(ListObj.Items[Itens]).Free;

And casting to TTestVO is overhead also.

To insert a code block place it inside the [ code ] .. [ /code ] (w/o spaces) - see BBCode help

Last edited by mpv (2017-11-16 21:40:41)

Offline

#3 2017-11-17 00:55:54

automacaosamos
Member
Registered: 2015-02-19
Posts: 20

Re: remove TList/ObjectList from memory

Perfect, thank you...

Offline

Board footer

Powered by FluxBB