簡體   English   中英

為何選擇QI分支?

[英]Prefs why QI the branch?

大家好,我正在嘗試連接首選項監聽器和其他內容,但是在代碼中我發現它們在不斷完善,我不知道為什么。 你們知道為什么嗎? 這些是我看到的代碼示例:

this._branch = Services.prefs.getBranch(branch_name);
this._defaultBranch = Services.prefs.getDefaultBranch(branch_name);
this._branch.QueryInterface(Ci.nsIPrefBranch2);

在上面他們沒有QI _defaultBranch,為什么呢? 為什么要使用nsIPrefBranch2而不是nsIPrefBranch

此代碼段來自xul學校: https : //developer.mozilla.org/zh-CN/docs/Adding_preferences_to_an_extension

 this.prefs = Components.classes["@mozilla.org/preferences-service;1"]
     .getService(Components.interfaces.nsIPrefService)
     .getBranch("extensions.stockwatcher2.");
 this.prefs.QueryInterface(Components.interfaces.nsIPrefBranch);
 this.prefs.addObserver("", this, false);

在這里,他們將QI變為nsIPrefBranch

我對所有方法都感到困惑,哪種方法正確?

nsIPrefBranch2是舊版接口,這些天繼承了nsIPrefBranch ,否則為 仍然存在,以便在Firefox 3.x天內編寫並因此使用nsIPrefBranch2 “舊”代碼不會中斷; 否則它將已經被刪除。 因此,任何不應在Firefox 3.x上運行的新代碼也不需要QI到nsIPrefBranch2

(順便說一句: nsIFilensILocalFile本質上是相同的故事)。

但是,從前, nsIPrefBranch2實際上添加了addObserverremoveObserver (現在是nsIPrefBranch一部分)。 因此,要使用addObserver您需要進行那些QI調用。 IIRC,使用新接口而不是擴展舊接口的原因是ABI(二進制)兼容性。 由於Firefox 4不保證主要版本之間的二進制兼容性,因此將兩個接口合並在一起。

getBranch().QueryInterfac(Ci.nsIPrefBranch)完全沒有意義。 我的猜測是代碼曾經在某個時候說nsIPrefBranch2 ,而作者后來做了一個自動化的nsIPrefBranch2 > nsIPrefBranch重寫...

因此,請重復:新代碼不需要QI到nsIPrefBranch2 ,當然也不需要再次將QI nsIPrefBranchnsIPrefBranch

我將您的示例重寫為:

this._branch = Services.prefs.getBranch(branch_name); // Already returns nsIPrefBranch
this._defaultBranch = Services.prefs.getDefaultBranch(branch_name); // Already returns nsIPrefBranch

和:

this.prefs = Services.prefs.getBranch("extensions.stockwatcher2.");
this.prefs.addObserver("", this, false);

PS:看來QI(Ci.nsIPrefBranch)代碼確實是自動重寫 我現在刪除了QI呼叫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM