AOwnsObjects = true 就是 objectlist釋放的時候,裡面的對象一并釋放。
TObjectList對象的建立方法有一個參數:
constructor TObjectList.Create(AOwnsObjects: Boolean);
從字面就可了解其意義:擁有對象集與否。幫助文檔:
If the OwnsObjects property is set to true (the default), TObjectList controls the memory of its objects, freeing an object when its index is reassigned; when it is removed from the list with the Delete, Remove, or Clear method; or when the TObjectList instance is itself destroyed.
這段話的意思就是TObjectList 的幾個删除方法和釋放方法都受參數AOwnsObjects的影響。我就常常用 TObjectList來管理對象,很友善。記得第一次用時,沒看文檔,用的預設參數值,重載其釋放方法,結果一直報錯,因為在DLL中實作,找了很久才找出緣由。
TList TObjectList的差別和使用。
1,所在的單元。
TList一直就是在Classes裡
TObjectList一直就是在Contnrs裡
2, TObjectList對象的建立方法有一個參數:
constructor TObjectList.Create(AOwnsObjects: Boolean);
從字面就可了解其意義:擁有對象集與否。幫助文檔:
If the OwnsObjects property is set to true (the default), TObjectList controls the memory of its objects, freeing an object when its index is reassigned; when it is removed from the list with the Delete, Remove, or Clear method; or when the TObjectList instance is itself destroyed.
這段話的意思就是TObjectList 的幾個删除方法和釋放方法都受參數AOwnsObjects的影響。
用的預設參數值,釋放時ObjectList裡的對象一塊釋放掉.
TList,TObjectList 使用——資源釋放
TOjectList = Class (Tlist);
TOjectList繼承Tlist,從名字上看就可以知道它是專門為對象清單制作的,那麼他到底豐富了那些功能呢?
首先是 TObject 作為對象可以友善使用,無需指針強制。
豐富了 Notify 針對目前狀态處理,比如如果是删除就将該點的引用一并清理掉;
procedure TObjectList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if (Action = lnDeleted) and OwnsObjects then
TObject(Ptr).Free;
inherited Notify(Ptr, Action);
end;
看notify方法會發現:如果TOjectList.OwnsObjects=True時(預設的建立),釋放的時候會連裡面的對象一塊釋放掉。
TOjectList.OwnsObjects=False時,釋放的時候不會釋放裡面的對象。
在 Tlist 中,有 Clear(),将呼叫 SetCount,SetCapacity;即删除所有。
procedure TList.Clear();
begin
SetCount(0);
SetCapacity(0);
end;
當該對象銷毀是,也會自動調用Clear() 清除所有。
destructor TList.Destroy;
begin
Clear();
end;
如果從 Tlist 繼承也必須實作 Notify() ,友善資源釋放,減少麻煩。
List和OjectList釋放的差別如下例子:
procedure TForm1.Button1Click(Sender: TObject);
var
list: TObjectList;
i: Integer;
btn: TButton;
begin
list := TObjectList.Create;
for i := 0 to 6 do
begin
btn := TButton.Create(Self);
with btn do begin
Caption := Format('Btn %d', [i+1]);
Parent := Self;
end;
list.Add(btn);
end;
ShowMessage('TObjectList 釋放時, 會同時釋放其中的對象');
list.Free;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
list: TList;
i: Integer;
btn: TButton;
begin
list := TList.Create;
for i := 0 to 6 do
begin
btn := TButton.Create(Self);
with btn do begin
Caption := Format('Btn %d', [i+1]);
Parent := Self;
end;
list.Add(btn);
end;
ShowMessage('TList 釋放後, 其中的對象并未釋放');
list.Free;
end;
如果用TObjectList來存儲,當調用sort方法時要注意先将owerobject設定為False
總結:如果有一個對象需要用到清單,最好從 TOjectList 開始繼承,對資源釋放有完善的處理機制。