How to list objects of a given class?

5

For example, let's say I have a class TConfiguracao .

Here the constructor and destructor attributes

and in some forms I create several T-type variables

conf1 :TConfiguracao;
conf2 :TConfiguracao;
...

conf1 := TConfiguracao.Create();
conf2 := TConfiguracao.Create();
...

In closing this form I do:

FreeAndNil(conf1);
FreeAndNil(conf2);

It is running 100%. What I would like to know is, is there any way to go through all the objects of this TConfiguracao class and apply a FreeAndNil without knowing for sure how many variables of this type I created? I know there is a way to traverse the components of a form this way

for i := 0 to Form.ComponentCount - 1 do
  begin
    if Form.components[i].classtype is  TEdit then
    begin
      //
    end;
  end;

But objects from other classes I can not. Is there any way to do this ??

    
asked by anonymous 04.11.2014 / 19:29

2 answers

3

Assuming a class and an event type:

TMyClass = class
private
    FIndex : Integer;
public
    //Crio um novo tipo TMyClassArray que representa um array dessa nova classe.
    type TMyClassArray = array of TMyClass;  
    // Crio uma variável de nome Instances que não vai fazer parte dos objetos criados, mas sim da classe. 
    // E por isso deve ser chamada atraves do identificador da classe. 
    class var Instances : TMyClassArray; TMyClass. 
    constructor Create;
    destructor Destroy;
    //Else code...
end;

And your builder:

constructor TMyClass.Create;
begin
    inherited;
    SetLength(Instances, Length(Instances) + 1);
    FI := Length(Instances) - 1;
    Instances[FI] := Self;
    //Else code...
end;

And its destroyer:

destructor TMyClass.Destroy;
var
    I : Integer;
begin
    //Else code...
    Instances[FI] := nil;
    I := FI;
    while(I <= Length(Instances) - 1)do
    beign
        Instances[I] := Instances[I + 1];
        Instances[I].FI := I;
        Inc(I);
    end;
    SetLength(Instances, Length(Instances) - 1);
    inherited;
end;

You can access TMyClass.Instances in your code to get all instances already created.

Note 1: The destructor may need better memory handling.

Note 2: The convention dictates that Instances is a class property and not class var as I just described it for convenience.

    
04.11.2014 / 19:58
2

What you can do is use a TObjectList . You must instantiate the TObjectList and then you can add your objects to this list using the Add method. When you destroy the TObjectList all objects added to it will be destroyed as well.
The OwnsObjects property of the TObjectList must be True (Default) so that you can destroy the objects. To destroy you can also use the Delete, Remove, or Clear method as well. *
Note: You have to add the unit Contnrs in uses. p>     

05.11.2014 / 13:10