Working with objects is pretty powerful, but requires to handle manually the
created instances life time, via try
.. finally
blocks. Most of the time, the TSQLRecord
life time would be very
short: we allocate one instance on a local variable, then release it when it
goes out of scope.
If we take again the TSQLBaby
sample, we may write:
function NewMaleBaby(Client: TSQLRest; const Name,Address: RawUTF8): TID;
var Baby: TSQLBaby; // store a record
begin
Baby := TSQLBaby.Create;
try
Baby.Name := Name;
Baby.Address := Address;
Baby.BirthDate := Date;
Baby.Sex := sMale;
result := Client.Add(Baby);
finally
Baby.Free;
end;
end;
To ease this pretty usual pattern, the framework offers some kind of
automatic memory management at TSQLRecord
level:
function NewMaleBaby(Client: TSQLRest; const Name,Address: RawUTF8): TID;
var Baby: TSQLBaby; // store a record
begin
TSQLBaby.AutoFree(Baby); // no try..finally needed!
Baby.Name := Name;
Baby.Address := Address;
Baby.BirthDate := Date;
Baby.Sex := sMale;
result := Client.Add(Baby);
end; // local Baby instance will be released here