在android 中存儲(chǔ)數(shù)據(jù)時(shí)經(jīng)常用SharedPreference, 并且在提交數(shù)據(jù)時(shí)一直用的是Editor的commit方法, 今天無(wú)意了看到了系統(tǒng)用了apply,看了方法的介紹, 原來(lái)這個(gè)方法也是可以提交數(shù)據(jù)的.
apply方法在官方SDK說(shuō)明如下:
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().
這兩個(gè)方法的區(qū)別在于:
1. apply沒(méi)有返回值而commit返回boolean表明修改是否提交成功
2. apply是將修改數(shù)據(jù)原子提交到內(nèi)存, 而后異步真正提交到硬件磁盤(pán), 而commit是同步的提交到硬件磁盤(pán)邦马,因此,在多個(gè)并發(fā)的提交commit的時(shí)候,他們會(huì)等待正在處理的commit保存到磁盤(pán)后在操作硅则,從而降低了效率厚者。而apply只是原子的提交到內(nèi)容条辟,后面有調(diào)用apply的函數(shù)的將會(huì)直接覆蓋前面的內(nèi)存數(shù)據(jù)冀偶,這樣從一定程度上提高了很多效率鬓梅。
3. apply方法不會(huì)提示任何失敗的提示吞获。
由于在一個(gè)進(jìn)程中况凉,sharedPreference是單實(shí)例,一般不會(huì)出現(xiàn)并發(fā)沖突各拷,如果對(duì)提交的結(jié)果不關(guān)心的話刁绒,建議使用apply,當(dāng)然需要確保提交成功且有后續(xù)操作的話烤黍,還是需要用commit的知市。