RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TObjectList Class

Ordered list of objects.

Pascal
TObjectList<T: class> = class(TList<T>);
C++
template <T: class>
class TObjectList : public TList<T>;

TObjectList represents an ordered list of objects, accessible by an index. 

TObjectList is a TList with the capability of automatically freeing object entries when they are removed from the list. When a TObjectList is instantiated, an AOwnsObjects parameter specifies whether the list owns the list entries. If the entry is owned, when the entry object is removed from the list, the entry object is freed. 

The OwnsObjects property gets or sets the object ownership.  

Delphi Examples: 

 

{
This example demonstrates the usage of the generic TObjectList class.
}
type
  { Declare a new object type }
  TNewObject = class
  private
    FName: String;

  public
    constructor Create(const AName: String);
    destructor Destroy(); override;
  end;

{ TNewObject }

constructor TNewObject.Create(const AName: String);
begin
  FName := AName;
end;

destructor TNewObject.Destroy;
begin
  { Show a message whenever an object is destroyed }
  MessageDlg('Object "' + FName + '" was destroyed!', mtInformation, [mbOK], 0);
  inherited;
end;

procedure TForm3.Button1Click(Sender: TObject);
var
  List: TObjectList<TNewObject>;
  Obj: TNewObject;
begin
  { Create a new List }
  List := TObjectList<TNewObject>.Create();

  { Set the OwnsObjects to true - the List will free them automatically }
  List.OwnsObjects := true;

  { Add some items up the List }
  List.Add(TNewObject.Create('One'));
  List.Add(TNewObject.Create('Two'));

  { Add a new item but keep the reference }
  Obj := TNewObject.Create('Three');
  List.Add(Obj);

  {
    Remove an instance of TNewObject class. Destructor
    should be called because we have set the OwnsObjects
    to true!
  }
  List.Delete(0);
  List.Extract(Obj);

  { Destroy the List completely - more messageboxes will be shown }
  List.Free;
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!