我想知道当我在Delphi中有一个TObjectDictionary时如何正确管理内存。
我想创建一个TShapes的ObjectDictionary来在Timage中绘制圆,但是圆的位置和数量会随着每个cicle的变化而变化。
我不想出现内存泄漏。在关闭表单中,我将执行FShapes.Free,但是我不确定是否每次都执行FShapes.Clear会发生内存问题。
我读到我必须在OnValueNotify上执行此操作,但是我不确定如何执行此操作。
private
FShapes: TObjectDictionary<Integer,TShape>;
procedure TFRemote_Layout.FormCreate(Sender: TObject);
begin
FShapes := TObjectDictionary<Integer,TShape>.Create([doOwnsValues]);
FShapes.OnValueNotify := VNotify;
end;
procedure TFRemote_Layout.FormClose(Sender: TObject; var action: TCloseaction);
begin
FShapes.Free;
end;
procedure TFRemote_Layout.InsertShape(i,x,y: Integer);
var
AShape: TShape;
begin
try
AShape := TShape.Create(nil);
AShape.Top := x;
AShape.Left := y;
FShapes.Add(i,AShape);
finally
//Free AShape??
end;
end;
procedure TFRemote_Layout.ClearDictionary();
begin
FShapes.Clear; //This clear frees all the memory for the next cycle?
end;
//I was reading in embarcadero something like this,but not sure
procedure TFRemote_Layout.VNotify(Sender: TObject; const Item: TShape; action: TCollectionNotification);
begin
Item.Free;
end;