开发者

Save TList of objects in text file

开发者 https://www.devze.com 2022-12-19 23:31 出处:网络
I have the following classes: type TSong = class(TObject) private FArtist: String; FTitle: String; procedure SetArtist(Artist: String);

I have the following classes:

type
  TSong = class(TObject)
  private
    FArtist: String;
    FTitle: String;
    procedure SetArtist(Artist: String);
    procedure SetTitle(Title: String);
  public
    property Artist: String read FArtist Write SetArtist;
    property Title: String read FTitle Write SetTitle;
    constructor Create(Artist, Title: String);
  end;
type
  TPlaylist = class(TList)
    private
      procedure ShowInListBox(Box: Pointer);
    public
      { Public-Deklarationen }
    end;

At runtime, I create instances of these classes:

Playlist := TPlaylist.Create;
Playlist.Add(TSong.Create('Artist 1', 'Title 1'));
Playlist.Add(TSong.Create('Artist 2', 'Title 2'));
Playlist.Add(TSong.Create('Artist 3', 'Title 3'));
Playlist.Add(TSong.Create('Artist 4', 'Title 4'));

When the program is closed, I would like to save these data into a text file. How can I do this?

The best way would probably be to create a procedure which belongs to the TPlaylist class, right?

procedure SaveToTxtFile(fName: String);

What should such a function exactly do? When the program is started again, I would like to be able to build the playlist again.

It would be nice if the data would be saved in a text file like this:开发者_运维百科

Artist 1///Title 1
Artist 2///Title 2


You're on the right track. What you're trying to do is called serialization, turning an object into a streamable form like a file.

You need to develop a format. Exactly what the format is doesn't matter, as long as it's consistent and preserves all of the data that you require to reconstruct the object. You say you want a text file, so you can take a bit of a shortcut in this case by using a TStringList, which has file IO built in.

Try something like this:

procedure TSong.Serialize(serializer: TStringList);
begin
  serializer.Add(format('%s///%s: %s', [Artist, Title, Filename])); //add a filename member! You need one!
end;

procedure TPlaylist.Serialize(const filename: string);
var
  serializer: TStringList;
  i: integer;
begin
  serializer := TStringList.Create;
  try
    for i := 0 to Count - 1 do
      TSong(self[i]).Serialize(serializer);
    serializer.SaveToFile(filename);
  finally
    serializer.Free;
  end;
end;

You'll also want to implement the inverse, deserialization. It shouldn't be too difficult.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号