知识就是力量,时间就是生命。这篇文章主要讲述SharedPreferences.Editor 的apply()与commit()方法的区别相关的知识,希望能为你提供帮助。
commit()的文档官方文档如下:
Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.
Note that when two editors are modifying preferences at the same time, the last one to call commit wins.
If you don‘t care about the return value and you‘re using this from your application‘s main thread, consider using apply() instead.
apply()的文档官方文档如下:
Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.
Note that when two editors are modifying preferences at the same time, the last one to call apply wins.
【SharedPreferences.Editor 的apply()与commit()方法的区别】Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won‘t be notified of any failures. If another editor on this SharedPreferences 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.
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.
解释说明
- 需要注意的是
commit()
方法是Added in API level 1
的,也就是sdk1
就已经存在了. apply()
方法是Added in API level 9
的.commit()
有返回值,成功返回true
,失败返回false
.commit()
方法是同步提交到硬件磁盘,因此,在多个并发的提交commit的时候,他们会等待正在处理的commit保存到磁盘后在操作,从而降低了效率。apply()
没有返回值.apply()
是将修改的数据提交到内存, 而后异步真正的提交到硬件磁盘.
推荐阅读
- Android Google AdMob 广告接入示例
- iWatch报错: Missing com.apple.developer.healthkit entitlement
- Android 解决方法数 65536 (65k) 限制
- Android WiFi直连并互发图片
- 使用逻辑门的布尔代数简化示例
- 页面SEO(如何使用Yoast SEO优化WordPress网站())
- WordPress如何使用WooCommerce创建电商网站(综合指南)
- 如何在WordPress网站上设置Google AMP(加速移动页面)
- 如何使用Wordfence Security免费保护WordPress网站(深入指南)