2021年5月29日 星期六

[Android] SharedPreferences string set 的坑

markdown 之前曾經遇過一個問題就是用 SharedPreferences 儲存 string set,我已經呼叫完 commit,但是 app 關掉重開之後,卻發現 string set 卻沒有寫入到,當時一直沒搞清楚是甚麼問題,最近偶然看到原來用 string set 有這樣一個坑,值得在這裡紀錄一下。 當時一直在想是 putStringSet 出了甚麼問題,但問題是出在 getStringSet return 的 string set,不能直接將資料加到這個 string set 傳給 putStringSet,因為 putStringSet 會比較傳進來的 string set 與 getStringSet return 的是不是同一個 object,如果是則不做任何動作。 這可能是為了效能考量,但其實挺違反直覺的,不注意真的很容易踩坑。 --- * [Misbehavior when trying to store a string set using SharedPreferences](https://stackoverflow.com/questions/14034803/misbehavior-when-trying-to-store-a-string-set-using-sharedpreferences/14034804#14034804) * [Android: String set preference is not persistent](https://stackoverflow.com/questions/16820252/android-string-set-preference-is-not-persistent) * [What's the difference between commit() and apply() in SharedPreferences](https://stackoverflow.com/questions/5960678/whats-the-difference-between-commit-and-apply-in-sharedpreferences)

沒有留言:

張貼留言