Freeing multiple Objects in delphi

delphi

Solution

With Delphi 2009, the TStringList constructor has an optional boolean parameter "OwnsObjects". If you set that to true, the objects are freed automatically.

Else you can do the following:

for i := Team.Count-1 downto 0 do begin
  Team.Objects.Free;
end;
Team.Free;

And by the way, public fields are discouraged. You beter use properties so you can control what access is possible to the fields. And you can add setter functions to validate the input.

type
  TPlayer = class
  private
    FName     : string;
    FPosition : string;
    FHits     : Integer;
    FAtBats   : Integer;
  public
    constructor Create(const AName, APosition: string );

    property Name: string read FName;
    property Position: string read FPosition;
    property Hits: Integer read FHits write FHits;
    property AtBats: Integer read FAtBats write FAtBats;
 end;

Problem

Below, I inserted a code written by Ray Konopka (part of the Coderage presentation). I am planning to use it, however, I am not sure how to clean (on the fly) multiple objects. All my attempts were unsucesfull and rendered memory leak. Any thoughts are appreciated. Thanks, ``` program stringlistDictionary; {$APPTYPE CONSOLE} uses Classes, SysUtils; type TPlayer = class public Name: string; Position: string; Hits: Integer; AtBats: Integer; constructor Create( Name, Position: string ); end; constructor TPlayer.Create( Name, Position: string ); begin inherited Create; Self.Name := Name; Self.Position := Position; Hits := 0; AtBats := 0; end; var Team: TStringList; Player, NewPlayer: TPlayer; I: Integer; function FindPlayer( const Name: string ): TPlayer; var Idx: Integer; begin Result := nil; if Team.Find( Name, Idx ) then Result := TPlayer( Team.Objects[ Idx ] ); end; begin {== Main ==} Writeln( 'StringList Dictionary' ); Writeln( '---------------------' ); Writeln; Team := TStringList.Create; try NewPlayer := TPlayer.Create( 'Aramis Ramerez', 'Third Base' ); NewPlayer.Hits := 120; NewPlayer.AtBats := 350; Team.AddObject( NewPlayer.Name, NewPlayer ); NewPlayer := TPlayer.Create( 'Derrick Lee', 'First Base' ); NewPlayer.Hits := 143; NewPlayer.AtBats := 329; Team.AddObject( NewPlayer.Name, NewPlayer ); NewPlayer := TPlayer.Create( 'Ryan Theriot', 'Short Stop' ); NewPlayer.Hits := 87; NewPlayer.AtBats := 203; Team.AddObject( NewPlayer.Name, NewPlayer ); Player := FindPlayer( 'Derrick Lee' ); if Player <> nil then Writeln( 'Player Found: ', Player.Name, ', ', Player.Position ) else Writeln( 'Player not found.' ); Writeln; Writeln( 'Active Roster' ); Writeln( '-------------' ); for I := 0 to Team.Count - 1 do Writeln( TPlayer( Team.Objects[ I ] ).Name, #9, TPlayer( Team.Objects[ I ] ).Position ); Readln; finally //!! Need to free the players. Team.Free; end; end. ```

Original source