----- Original Message ----- From: "Bart" <bartjun...@gmail.com>
To: "FPC-Pascal users discussions" <fpc-pascal@lists.freepascal.org>
Sent: Wednesday, April 01, 2009 10:12 PM
Subject: [fpc-pascal] TList: newbie question


Hi,

I never used TList before, so I'm not sure if this is correct.

I constructed a TlcTextCache class that basically stores objects of
type TLcText in a TList.
A TlcText object is create with TLcText.Create(FileName).

My questions:
- I add my TlcText objects to the list by TList.Add(SomeTlcTextObject)
- I read from the list by SomeTlcTextObjetc :=
TlcText(TList.Items[Index]) (casting it at compiletime)
Is this the way I am supposed to do that and is it safe explicitly
casting the TList.Item[Index] to the TlcText type (I know I only add
this type of objects to the list).

Here's the relevant part of the code:

 TLcText = class
 [snip]

 TLcTextCache = class
 private
   FCacheList: TList;
 protected
   function IsCached(const FileName: String): Boolean;
   function CacheIndex(const FileName: String): Integer;
   function AddFile(const FileName: String): Boolean;
   function GetCacheCount: Integer;
   function GetLcText(const FileName: String): TLcText;
 public
   constructor Create; virtual;
   destructor Destroy; override;
   property Count: Integer read GetCacheCount;
 end;

{ TLcTextCache }

function TLcTextCache.IsCached(const FileName: String): Boolean;
begin
 Result := CacheIndex(FileName) >= 0;
end;

function TLcTextCache.CacheIndex(const FileName: String): Integer;
var
 i: Integer;
 LcText: TLcText;
begin
 Result := -1;
 for i := 0 to FCacheList.Count - 1 do
 begin
   LcText := TLcText(FCacheList.Items[i]);
   if LcText.FileName = FileName then
   begin
     Result := i;
     Break;
   end;
 end;
end;

function TLcTextCache.AddFile(const FileName: String): Boolean;
begin
 Result := FCacheList.Add(TLcText.Create(FileName)) >= 0;
end;

function TLcTextCache.GetCacheCount: Integer;
begin
 Result := FCacheList.Count;
end;

function TLcTextCache.GetLcText(const FileName: String): TLcText;
var Index: Integer;
begin
Index := CacheIndex(FileName);
if (Index >= 0) then
  Result := TlcText(FCacheList.Items[Index])
else
  Result := nil;
end;

constructor TLcTextCache.Create;
begin
 inherited Create;
 FCacheList := TList.Create;
end;

destructor TLcTextCache.Destroy;
var
 i: Integer;
 LcText: TLcText;
begin
 for i := FCacheList.Count - 1 downto 0 do
 begin
   LcText := TLcText(FCacheList.Items[i]);
   LcText.Free;
   LcText := nil;
 end;
 FCacheList.Free;
 inherited Destroy;
end;


So far testing this construction gave no obvious errors (but as we all
know that is no garantee that the code is not flawed at some point)
and no memory leaks (using heaptrc).

Bart

As far as I can see it all looks A-OK :)
cheers,
Paul
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
http://lists.freepascal.org/mailman/listinfo/fpc-pascal

Reply via email to