sharedPreferences apply() 保存上面所有的还是只保存最后一个?怎么运行的?

sharedPreferences apply() saves all the above or just the last one? How it works?

我的问题很简单,但我没有找到答案(抱歉,如果它在某个地方,只是没有找到)。

sharedpreferences.editor.apply() 是如何工作的?

为了清楚起见,我有以下代码:

MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.apply();
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();

这适用于我的项目。但是,在性能方面,在上面使用这个还是在下面使用这个更好?

MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();

基本上,上面的代码是正确的?
它适用于上面的所有 putSomething 还是 apply() 只适用于一个 putSomething

肯定是最后一个。 apply()commit() 都将保存所有更改。为什么您甚至想要多次应用更改?尽管最后一个在性能方面更好,但您不会真正注意到,因为 apply() 是 aSync。但是,不要做不必要的事情。但是 commit() 会降低性能,因为它不是同步的。

调用 apply() 一次保存对编辑器对象所做的所有更改。所以下面的代码是正确的。 =)

上面的代码是最好的,方法 apply() 将保存所有 SharedPreferences.Editor 更改,不需要每次都调用它。

无效申请()

将您的首选项更改从该编辑器提交回它正在编辑的 SharedPreferences 对象。这会自动执行请求的修改,替换 SharedPreferences 中当前的任何内容。

请注意,当两个编辑器同时修改首选项时,最后一个调用应用的优先。

如果您想了解使用 SharedPreferences 的最佳方式,请访问此站点:

Best Practices

还有一些文档:

Documentation

申请与提交

使用 apply() 和 commit() 的主要区别

.apply() 将在后台线程中保存您的更改。

.commit() 将在主线程中保存您的更改。

这两种方法将产生相同的结果。