-2

Edit: The HOW is not important, I'm interested in the WHY. Here is a scenario that triggers the WHAT:

I am loading a simply boolean value from UserDefaults.standard in my ViewController's viewWillAppear method. I do not alter or delete the data, I simply load it into a variable. e.g.:

var aBool:Bool? = UserDefaults.standard.bool(forKey: "MyBoolKey")

In the VC lifecycle, viewWillAppear and viewDidAppear a guaranteed to be called once, but might be called multiple times.

In my case with this particular view controller, they are called 3 times in rapid succession. For whatever reason, on the first time these functions are called, the bool (aBool) is set and loaded from UserDefaults properly. But the 2nd and 3rd time these functions are called, UserDefaults is returning nil, and in fact no other variables stored in UserDefaults are accessible, they all return nil if you inspect them from lldb when stopping the code on the 2nd and 3rd executions.

Why is UserDefaults working on the 1st iteration, but not the 2nd or 3rd?

smakus
  • 1,107
  • 10
  • 11
  • The real question is why are these methods being called multiple times? They will only be called when your view controller appears. It sounds like you may be presenting or allocating multiple instances of your view controller. Solve that first. – Paulw11 Aug 25 '23 at 11:45
  • There is nothing to solve. I’m asking what the limitations are with UserDefaults in the context of the view controller, which apparently nobody knows. – smakus Aug 26 '23 at 03:19
  • There is no limitation. The fact that the view lifecycle methods are being called unexpectedly indicates that there is something wrong with your code. It is quite possible that this is impacting your results, which is why I suggested looking into that – Paulw11 Aug 26 '23 at 05:49
  • Perhaps I should have titled my question “why does this break userdefaults”? The how is not important, the why is what I’m interested in. If you don’t know, that’s ok. I doubt many know the intricacies of userdefaults behind the scenes. – smakus Aug 27 '23 at 06:25
  • Probably unrelated to the question but `bool(forKey:)` returns **always** a non-optional. The annotation `Bool?` is pointless – vadian Aug 28 '23 at 16:49
  • Correct, it is unrelated. If you use value(for..., it will return nil. – smakus Aug 29 '23 at 18:51

0 Answers0