Scoreboard using Global Variable or Singleton
For the iPad program I am writing, I am using a开发者_如何学Python modal view as way for the user to access a scoreboard. The score is kept manually. On the Scoreboard view I have a button to increase the score and one to decrease the score which update a UILabel to show the updated score. There is a third button to close the scoreboard and the modal view is dismissed.
During game play, I access the scoreboard and update the score. Then I close the scoreboard and continue gameplay. Gameplay consists of accessing several views using a UINavigationController. When I access the scoreboard later in the game, the score is reset to 0.
How should a variable be stored, so when the scoreboard is accessed it retains the score that the user has set?
I have been doing research on global variables, singletons, and a few other methods. There seems to be a lot of debate of how this should be done. Since the scoreboard is accessed from several different views, I'm not sure how to store the score variable.
Any suggestions would me much appreciated.
Personally, I think that it's best to avoid the use of a global variable for this because it breaks encapsulation and it may not be necessary to use a singleton (and better to avoid it in most cases, in my opinion).
One possibility that may work for you (from what your description says) would be to subclass UINavigationController and have an instance variable for your scoreboard view in the subclass. It sounds like the scoreboard view is always being accessed from a view that is being controlled by the navigation controller. Whatever view controller is going to invoke the scoreboard view can get the navigation controller object and use its scoreboard object (which will have the current score) as the modal view.
It's also not clear to me whether the UILabel that is displaying the score is part of the scoreboard view or if it belongs to another view. If it belongs to another view it may also be possible to retrieve the score from the UILabel and then update it.
If you need the score to persist then you could user NSUserDefaults to store the score.
Hope this helps.
精彩评论