android - 为什么发明了新的 apply() 而不是修改 commit() 行为?

标签 android

阅读 SharedPreferences.Editor.apply() 上的文档我的理解是 apply() 的行为与 commit() 完全相同,但对算法进行了优化以防止 ANR 等。

文档明确指出用 apply() 替换 commit() 是安全的,并且 lint 鼓励我们这样做。

所以问题是为什么他们设计了 apply() 而没有修改 commit() 呢?

最佳答案

So the question is why they have devised the apply() and haven't modified commit() instead?

commit() 返回一个 bool 值。引用the documentation , bool 值是:

true if the new values were successfully written to persistent storage.

如果将 commit() 修改为异步,则它无法返回 boolean 来指示成功的写入操作,因为在返回值时,写入状态尚不清楚。

同时,他们不能修改 commit() 以返回 void 或某些 Future 东西或其他东西,因为这会破坏二进制文件与认为 commit() 将返回 boolean 的应用程序兼容。使用现有 commit() 的现有应用将失败,并出现 VerifyError 或尝试使用非以下内容调用 commit() 时出现的类似情况: bool 值返回值。

此外,Java 不允许两个方法具有相同的名称和不同的返回值。因此他们不可能有两个版本的 commit(),除非他们人为地添加了参数或其他东西。

因此,他们创建了 apply()

关于android - 为什么发明了新的 apply() 而不是修改 commit() 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28365268/

相关文章:

android - 触发 Android 股票彩信应用程序发送待处理消息

android - XML 中的 SimpleDraweeView 圆角

java - Android,在启动模拟器时启动应用程序

iphone - 如何在 Android 和 iOS 之间进行代码共享

android - 更改 AlertDialog 中超链接的颜色

android - Stripe PaymentMethodsActivity 添加谷歌支付按钮

android - 如何在sqlite db中部署android应用程序?

android - Android 3.0+系统栏如何添加自定义按钮?

android - Video.js 搜索在 Android 设备上关闭了大约 5-10 秒

java - spotify web api授权代码授予thelinmichael/spotify-web-api-java android