我在 Delphi 的接口上苦苦挣扎。这个问题可能是微不足道的,但我是德尔福的新手,所以请原谅。
我有一个带有自定义节点的 TreeView,它包含一个对象的接口(本质上,就像这里提出的那样:Storing interface pointer inside tree view nodes)。
问题是,一旦我删除了一个节点(为了重绘树视图)并将接口变量设置为 nil(由于某种我还没有完全理解的原因,释放不会与接口有关),最奇怪的事情就会发生:
在我的对象中,它包含一个列表、一个整数和一个字符串变量,字符串和列表将设置为空,而整数保持不变。
我无法解释这一点。有谁知道解决方法或这种行为的可能原因?顺便说一句,我使用的是 Delphi 10.2 Tokyo。
这是我相当不起眼的破坏方法:
myNode.destroy;
begin
intf:= nil;// intf holds the interface to the object
end;
编辑:这是我的代码的简化版本:
我指的对象:(我有几个类似的类,它们看起来像 obj 但略有不同,我不知道接口中会存储哪一个,但都共享这些变量)
Obj = class(InterfacedObject, IMyinterface)
count: integer; //this remains the same
children: array of ChildObj; //this will be emptied
name: string; //this will be set to ''
procedure addChild;
procedure IMyInterface.add = addChild;
end;
我定制的treeNode:
MyNode = class(TTreeNode)
Intf: IMyinterface;
destructor destroy; override;
end;
在我的班级里面管理 TreeView:
MyForm.ReloadTree;
begin
if myTreeView.Items.Count > 0 then
begin
myTreeView.Items.Clear;
end
for I:= 0 to RootObj.Count-1 do
begin
myTreeView.Items.AddChild(MyTreeview.Items[0], RootObj.Children[i].name);
(myTreeView.Items[0][i] as MyNode).Intf := Intf(RootObj.Children[i]);
//I will proceed iterating over all children and their children, doing
//the same process, a level higher in the treeView
//...
end;
end;