1
votes

I am new to swift and app development, and have a question about how to best organize data for a simple app.

I have a data model defined for an object, Choice.

The app has multiple view controllers. Two of these access/modify an array of Choices. Others access and modify a single choice from this array. So, they all work from this one data set, to varying degrees.

Right now, one of these view controllers (a table view) pretty much "owns" and saves the data. The rest of the view controllers just pass the data back and forth, which is getting a bit crazy.

What I'd like to do is have one data source that they are all accessing. But I don't want to use globals in the AppDelegate.

My current thinking is that I'll create a parent class for all of these view controllers to inherit from. This class will own the data and all the data handling functions.

Does this general organization work, and is it consistent with best practices? Is there another way that would be better for solving this problem? Any advice that you have would be greatly appreciated. Thanks!

1

1 Answers

2
votes

The approach you mentioned where you have a base view controller, is not a suitable one here and also deriving from it will create problems like duplicating the data and also potentially cause issues if you want to access data elsewhere from a non view controller.

You will need to have a model layer that will enable a controlled access to your model (data) objects. For instance, you can think of a model class say ChoiceManager and make it a Singleton.

class ChoiceManager{

  //The singleton instance
  static let sharedInstance = ChoiceManager()

  var choices : [Choices] = []

  //Logic to create Choice objects - may be parsing from a JSON, or from a network etc



}

Now across your project, you can access to the same ChoiceManager, by just saying

ChoiceManager.sharedInstance

And also access choices:

ChoiceManager.sharedInstance.choices