How to save data between screens of an iOS application?

I have some rows of data that from one screen of my application that I would like to store (in the model) and then retrieve if the user moves back to the same page. Right now, the data is becoming well-remembered in the model, however I ran into a problem because it seems that every time you return to the screen, you generate a new instance of the controller. Thus, my model does not have anything good because I am losing the reference to it (it is currently stored as an instance variable inside my controller). What am I doing wrong?

+4
source share
4 answers

What am I doing wrong?

Usually you will have a model (which can be a collection of objects, not just one) that are shared between your document or application. When a view controller is created, it is given a reference to the model (or to some part of the model). If he, in turn, creates another view controller, he passes the model reference to this object. Thus, the model is shared by all view controllers. The model is not forgotten when the view manager is freed up because other controllers are aware of this.

It looks like you have the beginning of the model, but it is limited to one controller. Perhaps you have the same situation with some of your other view controllers. Think about how you can link all these small models together with a larger object. This will make it easier to remember and also make it possible to assign responsibility for keeping the entire model in one object, such as an application delegate or a root view controller.

+3
source

It looks like you need to save model data to disk, possibly using NSUserDefaults, which is the most suitable storage mechanism for small amounts of data like this.

0
source

There are at least the following few options that you might consider:

  • As Andrew said, save data to disk through NSUserDefaults.
  • Use the singleton simulation template to create a data manager object that will store data throughout the life of the application.
  • Trying to find out why a new instance of your view controller is being created (which may be obvious or not so obvious in light of your code) and try to do something different to reuse a view controller (which can be simple or complex in light of your code )

Given that you are using the storyboard described by your comment, I would consider option 2, unless you want the changes to appear on your controller.

0
source

When you click the view controller on the navigation, and then return to it, it is saved . But if you want some data to be stored on multiple screens, a good singleton idea.

0
source

Source: https://habr.com/ru/post/1412665/


All Articles