I am creating an iPhone application, a game, and I am trying to understand and embrace the MVC architecture. I am planning to create a model, in this case called HighScoresModel
that is responsible for holding all the information about high scores in my game.
- Where should this model be created? In the AppDelegate? In the first view controller?
- How should other view controllers access the model in order to pass messages like
addScore:withDifficulty:
?
I think the best option to to have a class method on HighScoresModel
that will access a single, shared instance of the model from any object that needs it.
This is superior to the other options because no controller is responsible for instantiating the model, and the controllers are not unnecessarily coupled to the app delegate either.
As an example:
@interface HighScoresModel : NSObject
+ (HighScoresModel *)sharedHighScoresModel;
...
@end
@implementation HighScoresModel
static HighScoresModel *SharedHighScoresModel;
+ (HighScoresModel *)sharedHighScoresModel
{
if (!SharedHighScoresModel)
{
SharedHighScoresModel = [[HighScoresModel alloc] init];
}
return SharedHighScoresModel;
}
...
@end
Hope this helps!
Create a Singleton and create the HighScoresModel in there. The singleton will be accessible from all ViewController.
As far as other view controller passing messages you'll be able to do something similar from anywhere within the controller.
[MySingleTon myHighScoresModel] addScore:myScore withDifficulty:myDifficulty];
See the following link for more reference to singleton http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/