Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TStringList's AddObject with integers?

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?
like image 890
IElite Avatar asked Aug 30 '11 01:08

IElite


1 Answers

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.
like image 92
RRUZ Avatar answered Oct 19 '22 07:10

RRUZ