TBedID =class(TObject)
public
bedid:integer;
end;
然后在一个过程中:
var
objBedID: TBedID
tl:TListItem;
begin
while …… do
begin
tl := bedview.Items.Add;
tl.Caption :=…;
objBedId:=TBedID.Create;
objBedId.bedid:= bedid;
tl.Data:=objBedId;
//在这里不能用objBedID.free回收堆空间
//但是问题是当退出这个过程之后,这个堆空间都没有了访问句柄或都说对象引用。
//这将导致内存泄漏
//那么如果该过程调用多次,会导致内存不足吗?
//如何解决这类问题的空间回收问题,谢谢。
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
LI: TListItem;
i: Integer;
Obj: TMyObject;
begin
ListView1.Items.Clear;
ListView1.Items.BeginUpdate;
try
for i := 0 to 5 do
begin
Obj := TMyObject.Create;
Obj.ObjectID := 100 + i;
LI := ListView1.Items.Add;
LI.Caption := ListItem + IntToStr(i);
LI.Data := Obj;
LI.SubItems.Add(Object + IntToStr(Obj.ObjectID));
end;
finally
ListView1.Items.EndUpdate;
end;
ShowMessage(All added, let us clear the objects. );
ListView1.Items.BeginUpdate;
try
for i := 0 to ListView1.Items.Count-1 do
begin
LI := ListView1.Items[i];
if LI.Data <> nil then
begin
LI.Data := nil;
LI.SubItems[0] := ;
end;
end;
finally
ListView1.Items.EndUpdate;
end;
ShowMessage(Ok, nothing left. );
end;
这样应该不会有问题的,如果要在其他地方释放,方法一样。
TObject(LI.Data).Free;
置不置为nil并不重要. 一般置为nil是为了防止再次释放时把自己搞糊涂搞不清哪些已经释放过了, 如果只释放一次根本不用置nil