I have a TObjectList with few elements. I have to replace one of them with one new at the same item (without change a count). I do the following:
procedure TForm1.Button1Click(Sender: TObject);
var
TObj: TObjectList;
LPoint: TPPoint;
i: integer;
begin
TObj:= TObjectList.Create;
try
for i:= 0 to 3 do
begin
LPoint:= TPPoint.Create(i, i+ 1);
TObj.Add(LPoint);
end;
LPoint:= TPPoint.Create(21, 22);
TObj.Items[1]:= nil;
TObj.Items[1]:= LPoint;
for i:= 0 to 3 do
begin
ShowMessage(IntToStr(TPPoint(TObj.Items[i]).X));
end;
finally
TObj.Free;
end;
end;
My question is: how can I free the replaced element in the memory? The help says "an Objekt will be freed if his Index will be reassigned". Is the command TObj.Items[1]:= nil; enough?
Thanks in advance for any information.
Here you perform two assignments, so the class attempts to free two items.
At this point the previous item is a non-nil reference added in your earlier loop. That object is thus destroyed.
When this line executes,
TObj.Items[1] = niland so theFreemethod is called onnil. Nothing happens.The bottom line is that your code is overcomplicated. You can replace
with
The class will destroy the object currently stored in
TObj.Items[1]and then replace it withLPoint. Just as you want.