-1

I've started to use the TCollection class in Delphi XE and I found the answer at Using TOwnedCollection descendant in Delphi to be a good starting point. TCollection manages a list of TCollectionItems. However I noticed that TCollection.Add doesn't seem to add an TCollectionItem to a Collections array and indeed my testing appears to confirm that. The code in TCollection itself is:

function TCollection.Add: TCollectionItem;
begin
  Result := FItemClass.Create(Self);
  Added(Result);
end; 

FItemClass is the object type that will be created and I thought added to the TCollection object. The Added() method is deprecated and appears to be an old notification method. Nowhere do I see the Result being added to the collection. How should one add a TCollectionItem to a TCollection?

Community
  • 1
  • 1
rhody
  • 2,274
  • 2
  • 22
  • 40
  • 1
    Isn't TCollection an abstract class? Maybe the descendants override one of the mwthods. Just a thought – DavidG Feb 20 '14 at 01:17
  • 1
    After looking through the source code I have a partial answer to the above question. The act of creating a TCollectionItem creates an entry in the TCollection object because the Collection object is passed to the CollectionItem constructor. I was forgetting to call the inherited method in the constructor because the inherited method in turn calls setCollection which does that actual adding. However I am still not entirely sure why Add is called Add. – rhody Feb 20 '14 at 01:19

1 Answers1

5

TCollectionItem.Create(Collection: TCollection) calls TCollectionItem.SetCollection, which adds the item to Collection:

procedure TCollectionItem.SetCollection(Value: TCollection);
begin
  if FCollection <> Value then
  begin
    if FCollection <> nil then FCollection.RemoveItem(Self);
    if Value <> nil then Value.InsertItem(Self);
  end;
end;

It's called TCollection.Add because it creates the collection item, and the item constructor adds the item to the containing collection. So TCollection.Add indeed creates the item (adding the item to itself in the process), and returns a reference to that newly created item. (You use that reference to set the properties of the TCollectionItem itself.)

Ken White
  • 123,280
  • 14
  • 225
  • 444