I am trying to use for in
to iterate a TObjectList
:
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, Contnrs;
var
list: TObjectlist;
o: TObject;
begin
list := TObjectList.Create;
for o in list do
begin
//nothing
end;
end.
And it fails to compile:
[dcc32 Error] Project1.dpr(15): E2010 Incompatible types: 'TObject' and 'Pointer'
It seems as though Delphi's for in
construct does not handle the untyped, undescended, TObjectList
an as enumerable target.
How do i enumerate the objects in a TObjectList
?
My current code is:
procedure TfrmCustomerLocator.OnBatchDataAvailable(BatchList: TObjectList);
var
i: Integer;
o: TObject;
begin
for i := 0 to BatchList.Count-1 do
begin
o := BatchList.Items[i];
//...snip...where we do something with (o as TCustomer)
end;
end;
For no good reason, i was hoping to change it to:
procedure TfrmCustomerLocator.OnBatchDataAvailable(BatchList: TObjectList);
var
o: TObject;
begin
for o in BatchList do
begin
//...snip...where we do something with (o as TCustomer)
end;
end;
Why use an enumerator? Just cause.
I'm not certain exactly what the question is driving at but to address the broad use of a TObjectList, the example initialisation code for a TObjectList might look like this: var List: TObjectList<TNewObject>; Obj: TNewObject; begin { Create a new List. } List := TObjectList<TNewObject>.Create (); { Add some items to the List.
One important difference when using a TObjectList compared to creating your own is the existance of the OwnsObjects property which tells the TObjectList whether it owns the objects you add to it and therefore consequently whether it should manage freeing them itself. Show activity on this post. Something like this?
Setting "OwnsObjects" to true will allow the object list to free the memory for each item in the list when the Tobjectlist is freed or removed from the list. Basic methods from Tlist such as add, delete, rearrange, locate, access, and sort remain accessible.
TObjectList expands Tlist by adding the option to take ownership for the Tobject items added to the list through the use of the "OwnsObjects" property. Setting "OwnsObjects" to true will allow the object list to free the memory for each item in the list when the Tobjectlist is freed or removed from the list.
Using generics you can have a typed objectlist (just noticed the comment but ill finish this anyhow)
And if you're looking for a good reason to use a TObjectList<T>
that reason will be that it saves you a lot of type casting in your code
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, Generics.Collections;
Type
TCustomer = class
private
public
//Properties and stuff
end;
var
list: TObjectlist<TCustomer>;
c: TCustomer;
begin
list := TObjectList<TCustomer>.Create;
for c in list do
begin
//nothing
end;
end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With