Sergio Villanueva
Sergio Villanueva

Reputation: 35

How to manage memory in TObjectDictionary in Delphi

I want to kn ow how to manage correctly the memory when I have a TObjectDictionary in Delphi.

I want to create one ObjectDictionary of TShapes to paint circles in an Timage, but the position and the number of the circles changes every cicle.

I don't want to have memory leaks. In the on closeform I will do FShapes.Free, but I'm not sure if everytime I do FShapes.Clear what happens with memory.

I've read that I have to do it on the OnValueNotify, but I'm not sure how to do it.

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;

Upvotes: 1

Views: 486

Answers (1)

TLama
TLama

Reputation: 76693

Clearing a TObjectDictionary (by calling Clear method) removes all the items from the collection. Ownership given in the constructor parameter then specifies whether the keys and/or the values will be released when the items are removed.

In your case having values owned, calling Clear releases all the contained TShape objects with no need for any additional notification listener (for the OnValueNotify event).

Upvotes: 3

Related Questions