3

I have M1 chip MacBook Air laptop. I set, remove and get value from UserDefaults.

Below code I set the value

UserDefaults.standard.setValue("my string", forKey: "UserEmail")

Get the value using valueforkey

UserDefaults.standard.value(forKey: "UserEmail")

Remove key from userdefaults using removeObject

UserDefaults.standard.removeObject(forKey: "UserEmail")

Even if I set the value through "UserEmail", I am not able to get the value. Strange thing happened if I run four to five times then sometime I got the value and sometime not in the simulator! I have searched on google, stack overflow and already spent so many hours on this issue but not find any solution.

It only worked if I run this on Actual Device and other laptop that doesn't have M1 chip.

Can anyone help me out What should I do so it will work fine in simulator and on my M1 chip laptop.

Yogesh Patel
  • 1,893
  • 1
  • 20
  • 55
  • Shouldn't be a M1 problem. Make sure you aren't accidentally resetting `UserDefaults` every time on startup. – aheze Sep 17 '21 at 15:56
  • No I am not restarting userdefault value. – Yogesh Patel Sep 17 '21 at 16:16
  • It's not reproducible in a playground or simulator for me. Any reason you are not using `UserDefaults.standard.string` when reading the value? – Joakim Danielson Sep 20 '21 at 21:04
  • No there Is not reason for this. I try this way too but not working for me! – Yogesh Patel Sep 21 '21 at 06:52
  • Well the bottom line is that you have not provided enough information to make this reproducible so unless someone has experienced (and solved) the exact same issue I don’t think this question can be answered. – Joakim Danielson Sep 21 '21 at 07:41
  • I cannot provide my code it's because of privacy. It's true that no one can help me with this details. I will try to solved this. Thank you :-) – Yogesh Patel Sep 21 '21 at 08:43
  • I also has this issue. stopped application and run again its lead to loss of data from userdefault. @YogeshPatel – Vishal Patel Mar 27 '23 at 18:30

2 Answers2

0

Try UserDefaults.standard.synchronize(), though it is a deprecated API. On a side note, if it works with this call, there is a bug on Apple and ARM chip side.

0

Check if you are working with a release scheme on your simulator: Edit Scheme -> Run -> Build Configuration that value should be in "Debug" and not in "Release". Also check the debug executable option.

enter image description here

Gastón Antonio Montes
  • 2,559
  • 2
  • 12
  • 15