這個例子當然是簡化,但基本上我有觸發另一種形式(frmSettings)與德爾福:存儲正確的方式對象獲取從TObjectList
function Execute(var aSettings: TSettings):Boolean
TSettings
是我自己的對象主要創建一個主要形式用於跟蹤設置的表單。
在這個新打開的窗體(frmSettings)中,我獲取TMyObjectList
,它是TObjectList
的後裔。 填上TMyObj
。
然後我用來自該TMyObjectList的值填充TListBox
。
代碼:
...
FMyObjectList : TMyObjectList;
property MyObjectList: TMyObjectList read getMyObjectList;
...
function TfrmSettings.getMyObjectList: TMyObjectList ;
begin
If not Assigned(FMyObjectList) then FMyObjectList := TMyObjectList.Create(True)
Result := FMyObjectList;
end;
function TfrmSettings.Execute(var aSettings: TSettings): Boolean;
begin
//Fill myObjectList
FetchObjs(myObjectList);
//Show list to user
FillList(ListBox1, myObjectList);
//Show form
ShowModal;
Result := self.ModalResult = mrOk;
if Result then
begin
// Save the selected object, but how??
// Store only pointer? Lost if list is destroyed.. no good
//Settings.selectedObj := myObjectList.Items[ListBox1.ItemIndex];
// Or store a new object? Have to check if exist already?
If not Assigned(Settings.selectedObj) then Settings.selectedObj := TMyObj.Create;
Settings.selectedObj.Assign(myObjectList.Items[ListBox1.ItemIndex];);
end;
end;
procedure TfrmSettings.FillList(listBox: TListBox; myObjectList: TMyObjectList);
var
i: Integer;
begin
listBox.Clear;
With myObjectList do
begin
for i := 0 to Count - 1 do
begin
//list names to user
listBox.Items.Add(Items[i].Name);
end;
end;
end;
procedure TfrmSettings.FormDestroy(Sender: TObject);
begin
FreeAndNil(FMyObjectList);
end;
存儲只是指針似乎不是一個好主意呢,因爲觸發設置再次形成,重新創建列表和原來的對象將丟失即使用戶點擊「取消「
因此,存儲副本似乎更好,使用assign來獲取所有屬性的正確性。首先檢查我是否已經有一個對象。
If not Assigned(Settings.selectedObj) then Settings.selectedObj := TMyObj.Create;
Settings.selectedObj.Assign(myObjectList.Items[ListBox1.ItemIndex];);
如果我這兩條線移動到一個方法,而不是像Settings.AssignSelectedObj(aMyObj:TMyObj)
這是否看起來是正確的還是我執行這個錯誤的方式? 需要更多/更少的東西?
我需要一些指導方針,所以我覺得更安全,我不打開內存泄漏和其他麻煩。
除了回顧一下代碼,真正的問題是:這是將我的SelectedObject存儲在settings類中的正確方法嗎?
如果沒有被定義(FMyObjectList)然後FMyObjectList.Create(真);是不正確的 - 你應該寫:如果沒有分配(FMyObjectList),那麼FMyObjectList:= TMyObjectList.Create(True); – 2011-01-31 16:09:18
@ A.Bouchez:的確如此。如上所述,它是示例代碼,所以有時候你會很難點擊刪除按鈕。感謝您指出它,編輯! – Bulan 2011-01-31 16:17:30