Reputation: 23
I have a project that requires use of pre-defined classes to communicate with a remote web service. The primary class contains standard fields plus an array of objects defined within a different class. Instantiating the main class doesn't instantiate the lower level class thus producing an AV. The code below is an executable sample of the issue, where attempting to insert data in the 'ProductLines' array produces the error.
The question is how to instantiate the array objects? Tried constructor, setlength() without success. Any guidance MUCH appreciated.
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Soap.InvokeRegistry;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
ProductLine = class(TRemotable)
private
Description: string;
Quantity: integer;
end;
ArrayOfProductLines = array of ProductLine;
Customer = class(TRemotable)
private
Name: string;
Comment: string;
ProductLines: ArrayOfProductLines;
end;
// Customer Class
// Name
// Comment
// ProductLines (array)
// ProductLine
// ProductLine
// .....
var
Form1: TForm1;
TObj : Customer; // Transfer object
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
TObj.Name := 'Test Name;';
TObj.Comment := 'Test Comment';
TObj.ProductLines[0].Description := 'Test Description 1'; // fails
here, how to instantiate?
TObj.ProductLines[0].Quantity := 1;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Close;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
TObj := Customer.Create;
SetLength(Tobj.ProductLines,1);
end;
end.
Upvotes: 2
Views: 165
Reputation: 34919
The question is how to instantiate the array objects?
SetLength(TObj.ProductLines,1);
This line creates the first element in an array and initializes it to nil.
In order to create the object, just do:
TObj.ProductLines[0] := ProductLine.Create;
Note that every instantiated element in the ProductLines
array must be manually destroyed to avoid a memory leak.
A note on naming conventions:
T
as the first letter. Example TCustomer
T
as the first letter. Upvotes: 6