Criando um objeto TString

 

A classe TString possui um método AddObject que adiciona uma string a lista e associa um objeto à string. Se esse objeto é uma string você irá precisar representar a string como um objeto.

 

type

  TString = class(TObject)

  private

    fStr: string;

  public

    constructor Create(const AStr: string);

    property Str: string read FStr write FStr;

  end;

 

constructor TString.Create(const AStr: string);

begin

  inherited Create;

  FStr := AStr;

end;

 

Então você pode utilizar isso para adicionar strings para  qualquer propriedade Object dessa forma:

 

var

  ostr: TString;

begin

  ostr := TString.Create('My string as object') ;

  ListBox1.Items.AddObject('Item string here', ostr) ;

end;

 

Para pegar a string:

 

ostr := TString(ListBox1.Items.Objects[0]).Str;

  

Lembre-se de liberar o objeto String da memória quando não precisar mais dele

 

for j := 0 to ListBox1.Items.Count - 1 do

begin

  TString(ListBox1.Items.Objects[j]).Free;

  ListBox1.Items.Objects[j] := nil;

end;