-1

In my application, I want to have a "brain" that keeps track of what's going on. That is - multiple view controllers need to be able to set values in this brain and get at its data too.

How would I go about implementing this? From what I can tell, making my brain a singleton class is an option, otherwise I'd have to declare the brain as a delegate in every view controller and assign the brain to it every time it's created, which seems quite messy.

jscs
  • 63,694
  • 13
  • 151
  • 195
Grant J
  • 1,056
  • 3
  • 10
  • 18

4 Answers4

3

Your answer is in your question as you said. Use Singleton pattern if you want to access an object from multiple objects and there is no need for more than one copy.

Bear in mind that you must keep your data thread-safe if you will have two or more objects in your code that will try to manipulate the "brain" at the same time.

giorashc
  • 13,691
  • 3
  • 35
  • 71
2

As for the Singleton pattern, you might like to read this What is so bad about singletons?

Make sure you design your app using the MVC pattern and you should be good. The "brain" is the model.

How your "model" behaves depends on your application.

Community
  • 1
  • 1
Paul de Lange
  • 10,613
  • 10
  • 41
  • 56
  • Interesting reading! If I don't use a singleton though, would I have to create my brain in one `ViewController`, and then pass it to any other views that might want to utilise it? – Grant J Jul 02 '12 at 11:09
  • 1
    Depends if that is what you want to do. The reason Brain is not a good analogy is because a brain can think (logic) and it can remember (memory), which are two different things. If you brain is doing logical tasks you don't even need an instance and if it is remembering you probably need some other model (CoreData, NSUserDefaults, iCloud, Files, Web Server etc.). Depends what you want to do. – Paul de Lange Jul 02 '12 at 11:45
  • Hmmm, maybe I'm approaching the problem incorrectly then. My "brain" needs to basically keep a score for each team in a game, and also keep track of where the player is in the game (i.e. whose turn it is). Any suggestions? Thanks in advance. – Grant J Jul 02 '12 at 12:17
  • Definitely try and understand the MVC pattern first and also utilize object-oriented programming more ie: Game, Team, Scoreboard, Player all sound very object-y to me. There may also be GameCenter to consider. – Paul de Lange Jul 02 '12 at 12:22
1

Singleton pattern is an option. Another option is NSUserDefault.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
1

Yes you are right Singleton is a good option. As i think you are dealing with low amount of data so singleton will be good and easy otherwise go for saving data in a database or NSuserDefaults.

Deepak
  • 348
  • 4
  • 14