阅读 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/