Release object in a function - Memory Leak

1

I'm starting in the DataSnap world and I came across a situation that can not find a solution.

My code is with memory leak, because I can not release the objects. if I release the objects the access error violated in the result.

function TServerMethods1.Teste(Key: string; ID: Integer): TFDJSONDataSets;
var
  Con  : TFDConnection;
  qry  : TFDQuery;
begin

   Con:= TFDConnection.Create(nil);
   qry:= TFDQuery.Create(nil);

    try
      qry.Connection:= Con;

      qry.SQL.Text:= Format('select id, nome from clientes where id = %d', [ID]);
      qry.Open;

      Result:= TFDJSONDataSets.Create;
      TFDJSONDataSetsWriter.ListAdd(Result, qry);

    finally
      FreeAndNil(qry);
      FreeAndNil(Con);
    end;
end;

I need to release the created objects [qry, con] but I can not.

    
asked by anonymous 27.07.2017 / 15:16

2 answers

1

The TFDJSONDataSets returns the result of the qry that is passed by reference. Therefore, you can not destroy it while Result is not delivered.

How to solve?

vDataSetX := TServerMethods1.Teste('stringX', integerX);
...
  usa o vDataSetX como precisar
...
vDataSetX .Close;
vDataSetX .Free;
vDataSetX  := Nil;

Since it has been passed by reference the Close , Free will terminate the connection, and Nil will release vDataSetX from memory.

    
28.07.2017 / 13:24
0

In the case of TFDQuery, prefer to use .Release instead of .Free. The .Release calls, internally, a routines for cleaning of data that the TFDQuery calls while it processes the request between other operations. If you call only .Free, it may have memory leaks.

As a rule: See if the object has a Release method and use it. If it does not, use .Free.

    
01.08.2017 / 22:33