SharedPreferences建议使用apply代替commit

如果不关心修改结果是否成功,请使用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.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容