I have an interfaced object defined thusly (a list of TStringList):
type
IMyList = IArrayList<TStringList>;
TMyList = TArrayList<TStringList>;
I create instances to this in a function and return them to the caller. Here I get such an instance then put save it into a TListBox.Items.Objects[] property for later reference, then display it. The idea is when someone clicks on the TListBox entry, I want to get this list from Objects[] and display it.
procedure do_something;
var
a_list : IMyList;
begin
. . .
a_list := get_some_data_in_a_list();
// (1)
listbox1.Items.Objects[n] := TMyList(a_list); // save ref in Items.Objects
ShowList( a_list );
. . .
end;
Here's the onClick handler for the listbox:
procedure TfrmMain.listbox1Click(Sender: TObject);
var
n : integer;
a_list : IMyList;
begin
n := listbox1.ItemIndex;
if (n < 0) then exit;
a_list := IMyList(listbox1.Items.Objects[n]); // (2)
ShowList( listbox1.Items[n], a_list );
end;
The problem is, at line (2) above, a_list
is NIL
. The interface is destructing the object after it's added to the Objects[] property.
If I add this at line (1) above:
a_list._AddRef;
then at line (2) a_list
shows up just as expected.
This seems like a hack that shouldn't be necessary, and it's probably caused by the cast to add the item into Objects[], which is required because its type is IMyList
which isn't derived from TObject
, whereas TMyList
is.
How can I make this work properly without resorting to this hack?