如何在Delphi中的TObjectDictionary中管理内存

我想知道当我在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;
yangshd 回答:如何在Delphi中的TObjectDictionary中管理内存

清除TObjectDictionary(通过调用Clear方法)将从集合中删除所有项目。然后,构造函数参数中给出的所有权指定了删除项时是否释放键和/或值。

在您拥有值的情况下,调用Clear会释放所有包含的<?php $input_array = array('a','b','c','d','e'); print_r(array_chunk($input_array,2)); ?> 对象,而无需任何其他通知侦听器(对于OnValueNotify事件)。

本文链接:https://www.f2er.com/3165725.html

大家都在问