Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update NSUserDefaults data in one ViewController changed in other ViewController

Tags:

ios

swift

I got two viewcontroller: MainController and OptionsController. OptionsController it can be reached through a button from MainController. In OptionsController is there some values that I can save with NSUserDefaults. These values are needed in MainController. If I change these values in OptionsController when I come back to MainController they don’t change, but if I launch MainController again, these values was changed correctly. It seems that when MainController becomes active again, after leaving OptionsController, viewDidLoad is no longer raised. How can I update the data in MainController, please?

like image 911
Paolovip Avatar asked Feb 18 '26 23:02

Paolovip


2 Answers

As rounak says, viewDidLoad is only called once in the life of a view controller. If you have code you want executed every time a view controller is shown, put it in viewWillAppear.

NSUserDefaultsis a fairly heavyweight way to pass info between in-memory objects (it writes to disk). If you don't need persistence between runs, one of the other options he suggested would be better. I'd suggest the delegate pattern or a completion block.

like image 136
Duncan C Avatar answered Feb 20 '26 13:02

Duncan C


viewDidLoad is called only once for a view controller. You can use NSNotification, KVO, blocks or something like a delegate pattern to get a callback in your MainController whenever the value changes inside the OptionsController.

You can otherwise write code in viewWillAppear which gets called each time you pop the options controller.

like image 43
rounak Avatar answered Feb 20 '26 12:02

rounak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!