Glen Morse
Glen Morse

Reputation: 2593

How to destroy an array of custom components

I have a destroy procedure for a custom component 'TCARD'. Then during runtime i create an array

Cards: array[1..20] of TCards

then i do some things... and at end of procedure i would like to destroy all the TCards in the array. How do i do this or do i have to do each one at a time like so.

cards[1].destroy;
cards[2].destroy;
....
cards[20].destroy;

Upvotes: 0

Views: 457

Answers (1)

whosrdaddy
whosrdaddy

Reputation: 11860

If you use TObjectList<T>, this will be done for you, all you need to do is destroy the list.

Uses
  Generics.Collections,
...

// define your list
Cards: TObjectList<TCard>;

...

// create list
Cards := TObjectList<TCard>.Create;
try
 // Create and add your card objects
 ACard := TCard.Create;
 Cards.Add(ACard);
 // do something with Cards
 ...
 // destroy cards - this will automatically free the objects owned by the list
finally
 Cards.Free;
end;

As an added bonus you can make your own custom object and add Card related functions to it.

type
  TMyCardList = class(TObjectList<TCard>)
  public
   // add needed behaviours
   function FindHighestCardBySuit(ASuit : TSuit) : TCard;
   procedure Shuffle;
   // etc ...
  end;  

If for some reason you don't want to use TObjectList, you can free the objects with a simple loop:

procedure FreeCards(Cards : TCards);

var
  Card : TCard;

begin
 For Card in Cards do
  Card.Free;
end;

Upvotes: 6

Related Questions