当使用'int ++'将值存储在sharedprefferences中时,该值保持不变

问题描述 投票:0回答:1

最近,我发现了共享首选项的奇怪行为:

我的代码必须获取某个存储值的值,将其加1并再次存储。所以我用了下面的代码:

int count = sharedPreferences.getInt("complBetterCount", 0);
editor.putInt("complBetterCount", count++);
editor.apply();

但是此代码未添加1。在我将其替换为以下代码后,它起作用了:

int count = sharedPreferences.getInt("complBetterCount", 0);
count++;
editor.putInt("complBetterCount", count);
editor.apply();

有人可以向我解释为什么吗?

java android sharedpreferences
1个回答
0
投票

由于count++count之后增加。您需要先++count才能递增。

int count = sharedPreferences.getInt("complBetterCount", 0);
editor.putInt("complBetterCount", ++count);
editor.apply();
© www.soinside.com 2019 - 2024. All rights reserved.