英文:
Is it bad leaving SharedPreferences & Editor open
问题
例如,你有这个类
private SharedPreferences sp
private SharedPreferences.Editor editor
protected void onCreate(..) {
this.sp = ...
this.editor = this.sp.edit();
}
这样做有问题吗?
英文:
e.g. you have this class
private SharedPreferences sp
private SharedPreferences.Editor editor
protected void onCreate(..) {
this.sp = ...
this.editor = this.sp.edit();
}
Is it bad to do that?
答案1
得分: 0
共享偏好设置是正常的,但编辑器不行。
只要您不调用编辑器的 commit 或 apply 方法,值就不会被写入 preferences.file,我认为在从 sp 中读取时也不会获取到这些值。
所以作为一种习惯,写入偏好设置值时始终这样做(Java)
sp.edit().putString(key, value).apply()
或者使用 putInt、putBoolean 等方法。
英文:
The shared preferences are ok, the editor isn't.
As long as you do not call editor's commit or apply, the values are not written to the preferences.file and I think you also will not get the values when reading from sp.
So as a habit, always do this when writing a preference value (Java)
sp.edit().putString(key, value).apply()
Or putInt, putBoolean etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论