this slowpoke moves

Map Strings to Items in Memory

Der folgende Code ordnet Texte einer Liste im Arbeitsspeicher zu, die mit einem Mausklick abgerufen werden können. Beendet man das Programm, wird die Liste im Speicher gelöscht.

// Data record
type
  TPerson = record
    Name: string[255];
    Vorname: string[255]
  end;
  // Pointer to data record
  PPerson = ^TPerson;
  
//

procedure TForm1.Button1Click(Sender: TObject);
var
  Person: PPerson;
begin
  // Alloc memory
  new(person);
  Person^.Name := Edit1.Text;
  Person^.Vorname := Edit2.Text;
  // Add item and object
  Listbox1.Items.AddObject(IntToStr(Listbox1.Items.Count + 1), TObject(Person));
  // DO NOT dispose memory. Only a reference to a pointer object is storded with
  // the listbox item
end;

procedure TForm1.ListBox1Click(Sender: TObject);
var
  Name, Vorname: string;
begin
if Listbox1.ItemIndex > -1 then
  begin
    // Caste TObject and access the fields of the record
    Name := PPerson(Listbox1.Items.Objects[Listbox1.ItemIndex])^.Name;
    Vorname := PPerson(Listbox1.Items.Objects[Listbox1.ItemIndex])^.Vorname;
    ShowMessage(name + ', ' + Vorname);
  end;
end;

procedure TForm1.FormDestroy(Sender: TObject);
var
  Loop: Integer;
begin
  // Dispose memory
  if Listbox1.Items.Count > 0 then
    for Loop := Listbox1.Items.Count - 1 downto 0 do
      Dispose(PPerson(Listbox1.Items.Objects[Loop]));
end;

Keine Kommentare:

Kommentar veröffentlichen

Beliebte Posts

Translate