SharedPreference.Editor的apply和commit 區(qū)別

在android 中存儲數(shù)據(jù)時經(jīng)常用SharedPreference, 并且在提交數(shù)據(jù)時一直用的是Editor的commit方法, 今天無意了看到了系統(tǒng)用了apply,看了方法的介紹, 原來這個方法也是可以提交數(shù)據(jù)的.

apply方法在官方SDK說明如下:

Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

Note that when two editors are modifying preferences at the same time, the last one to call apply wins.

Unlike commit, which writes its preferences out to persistent storage synchronously, apply commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won’t be notified of any failures. If another editor on this SharedPreferences does a regular commit while a apply is still outstanding, the commit will block until all async commits are completed as well as the commit itself.

As SharedPreferences instances are singletons within a process, it’s safe to replace any instance of commit with apply if you were already ignoring the return value.

You don’t need to worry about Android component lifecycles and their interaction with apply() writing to disk. The framework makes sure in-flight disk writes from apply() complete before switching states.

The SharedPreferences.Editor interface isn’t expected to be implemented directly. However, if you previously did implement it and are now getting errors about missing apply(), you can simply call commit from apply().

這兩個方法的區(qū)別在于:

1. apply沒有返回值而commit返回boolean表明修改是否提交成功

2. apply是將修改數(shù)據(jù)原子提交到內(nèi)存, 而后異步真正提交到硬件磁盤, 而commit是同步的提交到硬件磁盤,因此,在多個并發(fā)的提交commit的時候,他們會等待正在處理的commit保存到磁盤后在操作,從而降低了效率。而apply只是原子的提交到內(nèi)容,后面有調(diào)用apply的函數(shù)的將會直接覆蓋前面的內(nèi)存數(shù)據(jù),這樣從一定程度上提高了很多效率。

3. apply方法不會提示任何失敗的提示。

由于在一個進程中,sharedPreference是單實例,一般不會出現(xiàn)并發(fā)沖突,如果對提交的結(jié)果不關(guān)心的話,建議使用apply,當然需要確保提交成功且有后續(xù)操作的話,還是需要用commit的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容