Using TStringList's AddObject with integers?

IElite picture IElite · Aug 30, 2011 · Viewed 14.6k times · Source

Using delphi 7:

  • How can I add an integer to the object portion of a stringlist item, using AddObject?
  • How can I retrieve the integer back from a object property of stringlist item?
  • How do I free all objects and list when done?

Answer

RRUZ picture RRUZ · Aug 30, 2011

Q: How can i add an integer to the object portion of a stringlist item, using AddObject?

A: Just cast the integer value to TObject

List.AddObject('A string',TObject(1));

Q:How can a retrieve the integer back from a object property of stringlist item?

A: Cast to integer the Object Value

AValue := Integer(List.Objects[i]);

Q: How do i free all objects and list when done?

A: You don't need free the object list, because you are not assigning memory. so only call the Free procedure of the TStringList.

Try this sample app

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils;


Var
  List : TStringList;
  i    : Integer;
begin
  try
    List:=TStringList.Create;
    try
      //assign the string and some integer values
      List.AddObject('A string',TObject(1));
      List.AddObject('Another string',TObject(100));
      List.AddObject('And another string',TObject(300));

      //Get the integer values back   

       for i:=0 to List.Count - 1 do
         Writeln(Integer(List.Objects[i]));

    finally
      //Free the list  
      List.free;
    end;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;

  Readln;
end.