如果不關(guān)心修改結(jié)果是否成功禁荒,請(qǐng)使用apply(),而不是commit()尔崔。
- commit() 是同步執(zhí)行的答毫。
- apply() 立刻修改內(nèi)存的值,但是提交到磁盤(pán)是異步操作的季春。
官方解釋
- 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.