轉載請標明出處:
http://www.lxweimin.com/p/7be25bfb4cb4
本文出自:
http://www.lxweimin.com/u/a1251e598483
在以往的開發中存儲數據時經常用SharedPreference, 并且在提交數據時一直用的是Editor的commit方法,今天看郭神的第一行代碼中舉例子用的都是apply。所以就想弄清楚,SharedPreference.Editor的apply和commit到底有什么區別。
下面是查的官方文檔
apply
void apply ()
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-memorySharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on thisSharedPreferencesdoes 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 SharedPreferencesinstances 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.
翻譯 :在編輯中調用 Editor 的提交方法 apply(),這將原子地執行所請求的修改,替換當前在SharedPreferences中的任何內容。
注意:當在同一時間有兩個 editors 修改 preferences的內容時,以最后一個修改的為準。
與 commit()方法不同的是 commit()方法是同步地儲存在磁盤上,apply()是先儲存在內存中,然后異步的儲存在磁盤上且不會有任何失敗的提示;如果apply()異步的內容尚未儲存帶磁盤上,另一個editor調用了commit()同步提交儲存,這個操作將會等待另一個commit()操作完成后才會真正執行。
由于SharedPreferences 在一個進程中是單例的,所以如果你不關心commit()成功與否的,完全可以用apply()來代替。
你不需要擔心Android組件生命周期及其與apply()寫入磁盤的交互。該框架確保來自apply()的在線磁盤寫入在切換狀態之前完成。
commit
boolean commit ()
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 commit wins.
If you don't care about the return value and you're using this from your application's main thread, consider using apply()
instead.
翻譯:在編輯中調用 Editor 的提交方法 apply(),這將原子地執行所請求的修改,替換當前在SharedPreferences中的任何內容。
注意:當在同一時間有兩個 editors 修改 preferences的內容時,以最后一個修改的為準。
如果你在主線程上調用此方法,且不關心儲存成功與否的返回值,你可以直接使用 appply() 。
兩個方法區別:
- apply沒有返回值而commit有返回表明修改是否成功
- apply是將修改數據原子提交到內存, 而后異步真正提交到硬件磁盤, 而commit是同步的提交到硬件磁盤,因此,在多個并發的提交commit的時候,他們會等待正在處理的commit保存到磁盤后在操作,從而降低了效率。而apply只是原子的提交到內容,后面有調用apply的函數的將會直接覆蓋前面的內存數據,這樣從一定程度上提高了很多效率。
- apply方法不會提示任何失敗的提示。
由于在一個進程中,sharedPreference是單實例,一般不會出現并發沖突,如果對提交的結果不關心的話,建議使用apply()。
詳細內容可以查看官方參考 :
https://developer.android.google.cn/reference/android/content/SharedPreferences.Editor.html