Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

TList Records....

Posted on 2004-08-29
6
Medium Priority
?
2,035 Views
Last Modified: 2011-08-18
Hi all

I am trying to teach myself how to work with records in a TList and am using the following code:

Type

    TRecord = ^TCard;

    TCard = packed record

            Item           : Integer;
            Name           : String;
            Limit          : Boolean;
            Period         : String;


end;


    Group  : TList;
    Record : TRecord;



// Add record

New(Record);

    Item           : Integer;
    Name           : String;
    Limit          : Boolean;
    Period         : String;

Group.Add(Record);
Record:=Nil;         <=== (Point Number 1 - see question 1 below)

RecordCount:=Group.Count-1;


Questions:

1: In above code at point number 1, I set Record to nil to delete the record since it is now in the TList - this is the correct way to do it (anything i should be aware of) ?

2: If i use Group.Delete(<record number>) how can i compress the list of records so that the unused memory of the deleted record is freed and RecordCount reflects the real number of records now in the TList?

A Grade A awaits anyone that can provide some information/help on this subject since i am still learning :)
0
Comment
Question by:foxjax
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 4

Accepted Solution

by:
Colin_Dawson earned 1000 total points
ID: 11927726
You don't need to set Record to Nil to delete it.  Record is a pointer to a memory address.  It's the memory address that stores the location of the actual record.

I never use .delete  it's really slow.  Instead do something like this...


Procedure DeleteRecord(const Idx: Integer);
var
  Loop: Integer;
  Record:TRecord;
begin
  Record := Group[Idx];
  Dispose(Record);           //This is the opposite to the New(Record) line.
  Group.Delete(Idx);
End;


That should just about do it. (I've not tested this code so it may not compile/be 100% accurate but it's close anyway)

Don't bother with your recordcount variable.  Group.Count will be accurate.  Just remember that it's the count not the reference to the highest index item.   The Highest item will always be one less than Group.Count.
0
 
LVL 6

Assisted Solution

by:bpana
bpana earned 200 total points
ID: 11927750
1. Record:=Nil;
It's ok what are you doing. You don't delete the Record, you deallocate the pointer, because Record in your case is a pointer to a TCard record structure.

2. When you use Delete, the TList automatically removes the item at the specified position from the list. You don't have to worry about the memory, because the memory will be freed automatically (by reference-counting). The new count will reflect on the list.
0
 
LVL 4

Assisted Solution

by:ceoworks
ceoworks earned 600 total points
ID: 11927789
Hi,

1.) Yes this is the way you should use.

Record := Group.Items[i];
Record := nil;
Group.Delete(i);

2.) TList is already doing that for you. I developed a little example about it :

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    btnAdd: TButton;
    btnDelete: TButton;
    lbRecs: TListBox;
    lblRecCount: TLabel;
    procedure FormCreate(Sender: TObject);
    procedure btnAddClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure btnDeleteClick(Sender: TObject);
    procedure lbRecsClick(Sender: TObject);
  private
    { Private declarations }
  public
    procedure RefreshRecCount;
  end;

  PMyRec = ^TMyRec;
  TMyRec = record
    Id: integer;
    Name: string[50];
  end;

var
  Form1: TForm1;
  IdCounter: integer;
  RecList: TList;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  RecList := TList.Create;
  IdCounter := 0;
end;

procedure TForm1.btnAddClick(Sender: TObject);
var
  NewRec: PMyRec;
begin
  Inc(IdCounter);
  New(NewRec);
  with NewRec^ do
  begin
    Id := IdCounter;
    Name := IntToStr(IdCounter) + '. Item';
  end;

  RecList.Add(NewRec);
  lbRecs.Items.Add(NewRec.Name);
  RefreshRecCount;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  RecList.Free;
end;

procedure TForm1.btnDeleteClick(Sender: TObject);
var
  i: integer;
  Rec: PMyRec;
begin
  i := lbRecs.ItemIndex; // selected item in TListBox
  Rec := RecList.Items[i]; // fills the record
  Rec := nil;

  RecList.Delete(i); // delete related record
  lbRecs.Items.Delete(i);
  RefreshRecCount;
end;

procedure TForm1.lbRecsClick(Sender: TObject);
var
  Rec: PMyRec;
begin
  Rec := RecList.Items[lbRecs.ItemIndex];
  Caption := Rec.Name;
end;

procedure TForm1.RefreshRecCount;
begin
  lblRecCount.Caption := IntToStr(RecList.Count);
end;

end.

object btnDelete: TButton
  Left = 452
  Top = 112
  Width = 75
  Height = 25
  Caption = 'btnDelete'
  TabOrder = 1
  OnClick = btnDeleteClick
end
object btnAdd: TButton
  Left = 452
  Top = 72
  Width = 75
  Height = 25
  Caption = 'btnAdd'
  TabOrder = 0
  OnClick = btnAddClick
end
object lblRecCount: TLabel
  Left = 452
  Top = 152
  Width = 58
  Height = 13
  Caption = 'lblRecCount'
end
object lbRecs: TListBox
  Left = 284
  Top = 72
  Width = 121
  Height = 97
  ItemHeight = 13
  TabOrder = 2
  OnClick = lbRecsClick
end

Personally, i think it's better to use classes instead of records. Everything will be more easier if you will choose this way..

TCard = class(TObject)
  private
    FId: integer;
    FName: integer;
  public
    property Id: integer read FId write FId;
    property Name: integer read FName write FName;
  end;

When you wants to add new items :

NewCard := TCard.Create;
with NewCard do
begin
  Item := 5;
  Name := '5. Card';
end;

Group.Add(NewCard);

When you wants to delete :

TCard(Group.Items[i]).Free;
Group.Delete(i);

You may use TObjectList instead of TList too..

Regards,

Oktay
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 4

Expert Comment

by:ceoworks
ID: 11927795
<1.) Yes this is the way you should use.

Record := Group.Items[i];
Record := nil;
Group.Delete(i);>

Sorry, i did wrong. You should use :

Dispose(Record) instead of Record := nil

Cheers,
0
 
LVL 4

Expert Comment

by:Evarest
ID: 11927957
As stated by others, it's better to use classes if possible. However if you stick to records (as i do often), you might better think twice about how you free your memory.

In many programs i've created, i've had huge memoryleaks just because i forgot to free some small record. A record can contain a small amount of information (some integers, ...) but can cause your RAM to fill up if you use it often...

In the following example, I'm going to use a separate object which will contain a list with records. These records contain your Card information. All this information will be properly freed when the Object is destroyed, or the list cleared. You'll also be enabled to request specific information from one single record.

Save the following in a new unit. I've not compiled it, but normally all should work properly...

[BEGIN CODE]

unit MyObject;

interface

uses
  WinTypes, Classes;

type
  PCard = ^TCard;
  TCard = record
   Item: Integer;
   Name: String;
   Limit: Boolean;
   Period: String
  end;


  TMyObject = class
  private
    fList: TList;

    function GetName(Index: integer): string;
    procedure SetName(Index: integer; const Value: string);
    function GetItem(Index: integer): string;
    procedure SetItem(Index: integer; Value: integer);
    function GetLimit(Index: integer): boolean;
    function GetPeriod(Index: integer): string;
    procedure SetLimit(Index: integer; const Value: boolean);
    procedure SetPeriod(Index: integer; const Value: string);
  public
    constructor Create;
    destructor Destroy; override;

    procedure AddRecord(const Name: string; I: integer);
    procedure DeleteRecord(Index: integer);
    procedure ClearRecords;
  published
    property Name[Index: integer]: string read GetName write SetName;
    property Item[Index: integer]: integer read GetItem write SetItem;
    property Period[Index: integer]: string read GetPeriod write SetPeriod;
    property Limit[Index: integer]: boolean read GetLimit write SetLimit;
  end;

implementation


{ TMyObject }

constructor TMyObject.Create;
begin
 inherited;
 fList :=TList.Create;
end;

destructor TMyObject.Destroy;
begin
 ClearRecords;
 FreeAndNil(fList);
 inherited;
end;

procedure TMyObject.SetName(Index: integer; const Value: string);
begin
 PCard(fList[Index])^.Name :=Value;
end;

procedure TMyObject.SetItem(Index: integer; Value: integer);
begin
 PCard(fList[Index])^.Item :=Value;
end;

procedure TMyObject.SetLimit(Index: integer; const Value: boolean);
begin
 PCard(fList[Index])^.Limit :=Value;
end;

procedure TMyObject.SetPeriod(Index: integer; const Value: string);
begin
 PCard(fList[Index])^.Period :=Value;
end;

function TMyObject.GetName(Index: integer): string;
begin
 result :=PCard(fList[Index])^.Name;
end;

function TMyObject.GetItem(Index: integer): integer;
begin
 result :=PCard(fList[Index])^.Item;
end;

function TMyObject.GetLimit(Index: integer): boolean;
begin
 result :=PCard(fList[Index])^.Limit;
end;

function TMyObject.GetPeriod(Index: integer): string;
begin
 result :=PCard(fList[Index])^.Period;
end;

procedure TMyObject.AddRecord( Item: integer; const Name: string;
                               Limit: boolean; const Period: string );
var
 MyRec: PCard; // thus a POINTER
begin
 new(MyRec); // reserve space for the record
 MyRec^.Name :=Name;
 MyRec^.Item :=Item;
 MyRec^.Limit :=Limit;
 MyRec^.Period :=Period;
 fList.Add(MyRec);
end;

procedure TMyObject.DeleteRecord( Index: integer );
begin
 if not (Index in [0..fList.Count-1]) then exit;
 Finalize(PCard(fList[Q])^);
 dispose(fList[Q]);
 fList.Delete(Q);
end;

procedure TMyObject.ClearRecords;
var
 Q: integer;
begin
 for Q :=fList.Count -1 downto 0 do
  begin
   DeleteRecord(Q);
  end;
end;

end.

[END CODE]

Take special interest in the following:

I've created a separate procedure to clear all records. This way you can easily clear all memory and no memory leaks will be left.

The Delete procedure contains:
 Finalize(PCard(fList[Q])^);
 dispose(fList[Q]);
 fList.Delete(Q);
This might seem somewhat overkill, but it'll definately free ALL memory. The Finalize will free the memory of the STRINGS and VARIANTS. This is important, as Dispose WILL NOT properly free strings and variants!

All the get and set procedures are private. You should get/set the info using the resp. properties.

HINT: if you quickly want to create the get/set procedures, you can use the following trick:

write in the interface section

property Limit[Index: integer]: boolean read GetLimit write SetLimit;

and hit CTRL+SHIFT+C

This will create all procedures which haven't been created yet. Thus here GetLimit & SetLimit will get an implementation and interface call! Quite handy if you have lots of Get/Set methodes to create...


Hope this was of some help to you...

Evarest
0
 

Author Comment

by:foxjax
ID: 11928706
Evarest - i tried to compile your code as it looked interesting but got a number of errors - ie: Published property 'Name' cannot be of type ARRAY.  I will post another question with some points for you as you did raise some interesting points for me to be aware of and if you then have the time and interest, i would be interested in working through the code to see if we can get a working model - for which of course i shall raise the points of the question.


To the others that answered, i say thank you - all of you.  I thought it fair that i raise the points and split them among each of you as follows:

Colin_Dawson - I used your code                                - 250 points
bpana             - Thanks for the input                           -   50 points
ceoworks        - I learned a little more from your code - 150 points
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question