如果不关心修改结果是否成功,请使用apply(),而不是commit()。
- commit() 是同步执行的。
- apply() 立刻修改内存的值,但是提交到磁盘是异步操作的。
官方解释
- If you don't care about the return value and you're using this from your application's main thread, consider using apply()
instead.
- Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in memory immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this 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.
网友评论