android SharedPreferences apply和commit的區別

1.apply沒有返回值而commit返回boolean代表修改是否提交成功2.apply是將修改數據原子提交到內存, 然後異步真正提交到硬件磁盤, 而commit是同步的提交到硬件磁盤3.apply方法不會提示任何失敗的提示

apply的效率高一些,若是沒有必要確認是否提交成功建議使用apply。


The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).html

 

 

 

調用 getSharedPreferences()獲取對應的的文件,該函數實現功能以下:android

 
  1. //Context類靜態數據集合,以鍵值對保存了全部讀取該xml文件後所造成的數據集合  
  2. private static final HashMap<File, SharedPreferencesImpl> sSharedPrefs =   
  3.        new HashMap<File, SharedPreferencesImpl>();   

能夠看到他有一個Map, 而針對SharedPreferencesImpl裏面,由會有map, 這樣也就能夠證實, 爲何SharedPreference被普遍使用了。 他在普通時刻,內容是從內存裏面直接讀取的, 只有在第一次啓動時,是IO操做。安全

 

2.  apply() 和 commit()的區別session

/**  boolean commit();的註釋以下:
* Commit your preferences changes back from this Editor to the
* {@link SharedPreferences} object it is editing. This atomically
* performs the requested modifications, replacing whatever is currently
* in the SharedPreferences.
*
* <p>Note that when two editors are modifying preferences at the same
* time, the last one to call commit wins.
*
* <p>If you don't care about the return value and you're
* using this from your application's main thread, consider
* using {@link #apply} instead. 若是你不考慮返回值,你在主線程中已經使用commit,那麼你能夠考慮替換使用apply
*
* @return Returns true if the new values were successfully written
* to persistent storage.
*/app

apply方法的註釋:框架

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

apply不一樣意commit,commit是同步的去更改硬盤上的東西,而apply是先直接更改內存中的, 而後異步的去更改應硬盤中的內容。async

不用去擔憂線程安全問題, 由於若是一個其餘的線程去commit,而恰好有一個尚未完成的apply,commit會被阻塞到異步線程提交完成。
*
* <p>As {@link SharedPreferences} instances are singletons within
* a process, it's safe to replace any instance of {@link #commit} with
* {@link #apply} if you were already ignoring the return value. 若是你真的能夠忽略返回值,剛好SharedPreferences又是單例模式的,那就能夠安全的用apply來替換commit
*
* <p>You don't need to worry about Android component
* lifecycles and their interaction with <code>apply()</code>
* writing to disk. The framework makes sure in-flight disk
* writes from <code>apply()</code> complete before switching
* states.  也不須要去關心android組件的聲明週期。 框架會保證完成全部apply以後,才切換狀態。ide

相關文章
相關標籤/搜索