commit()︰立刻同步寫入數據到磁碟中的SharedPreferences,並且具有回傳值(boolean)表示成功或失敗
apply()︰API 9之後加入的method,會將欲寫入的數據暫存於記憶體中,進行一個非同步寫入,因此速度較commit()快,但是不具有傳回值
因此假如不需要傳回值的時候,建議使用apply()取代commit()
Android Developer的解釋如下︰
Reference: http://developer.android.com/reference/android/content/SharedPreferences.Editor.htmlAs 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.
沒有留言:
張貼留言