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.