我想知道当我在 Delphi 中有一个 TObjectDictionary 时如何正确管理内存。
我想创建一个 TShapes 的 ObjectDictionary 来在 Timage 中绘制圆圈,但每个圆圈的位置和数量都会发生变化。
我不想发生内存泄漏。在 on closeform 中,我将执行 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;
最佳答案
正在清除TObjectDictionary
(通过调用 Clear
方法)从集合中删除所有项目。构造函数参数中给出的所有权指定在删除项目时是否释放键和/或值。
如果您拥有值,请调用 Clear
释放所有包含的 TShape
对象,无需任何额外的通知监听器(针对 OnValueNotify
事件)。
关于dictionary - Delphi中TObjectDictionary如何管理内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58696145/