上色

Code Block

2015年6月17日 星期三

[Android] commit()與apply()

SharedPreferences.Editor中的commit()與apply()都是向SharedPreferences寫入數據,差別如下︰

commit()︰立刻同步寫入數據到磁碟中的SharedPreferences,並且具有回傳值(boolean)表示成功或失敗

apply()︰API 9之後加入的method,會將欲寫入的數據暫存於記憶體中,進行一個非同步寫入,因此速度較commit()快,但是不具有傳回值

因此假如不需要傳回值的時候,建議使用apply()取代commit()

Android Developer的解釋如下︰
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.
 Reference: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html

沒有留言:

張貼留言