Destroying TADODataset created in runtime

荒凉一梦 提交于 2019-12-11 21:20:03

问题


I have a function that returns a TADODataset object:

// inside DataModule:

function TDM.GetWorkstationsList: TADODataset;
var
  DS: TADODataSet;
begin
  DS := TADODataSet.Create(nil);
  DS.Connection := MyConnection;  // MyConnection is TADOConnection
  DS.CommandType := cmdText;
  DS.CommandText := 'SELECT * FROM Workstation';
  DS.Active := True;
  Result := DS;
end;

This is how I plan to use it:

// inside main form: 

tvWorkstation.DataController.DataSource.DataSet := DM.GetWorkstationsList; // tvWorkstation is TcxGridDBTableView

As far as I know, if I create an object manually in runtime, I must destroy it manually at some moment to avoid memory leaks. How and when should I destroy my created dataset?


回答1:


You can simply make use of Delphi's ownership mechanism. You can pass in an owner (of type TComponent) in the constructor and then your data set will be destroyed whenever the owner is destroyed. In your case, just pass the form as the owner.

function TDM.CreateWorkstationsList(Owner: TComponent): TADODataSet;
begin
DS := TADODataSet.Create (Owner);
...
end;

DataSource.DataSet := DM.CreateWorkstationsList (Self);

You could also destroy the data set manually, for example in the form's OnDestroy event.



来源:https://stackoverflow.com/questions/19979198/destroying-tadodataset-created-in-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!