从视图控制器访问模型? [英] Accessing the model from the viewcontrollers?

查看:77
本文介绍了从视图控制器访问模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个iPhone应用程序,一个游戏,并且试图理解和拥抱MVC架构.我打算创建一个模型,在本例中称为HighScoresModel,该模型负责保存游戏中所有有关高分的信息.

  1. 应在何处创建此模型?在AppDelegate中?在第一个视图控制器中?
  2. 其他视图控制器应如何访问模型以传递诸如addScore:withDifficulty:之类的消息?

我认为在HighScoresModel上具有类方法的最佳选择是,该方法将从需要它的任何对象访问模型的单个共享实例.

这优于其他选项,因为没有控制器负责实例化模型,并且控制器也不必不必要地耦合到应用程序委托.

例如:

@interface HighScoresModel : NSObject

+ (HighScoresModel *)sharedHighScoresModel;
...

@end

@implementation HighScoresModel

static HighScoresModel *SharedHighScoresModel;

+ (HighScoresModel *)sharedHighScoresModel
{
    if (!SharedHighScoresModel)
    {
        SharedHighScoresModel = [[HighScoresModel alloc] init];
    }

    return SharedHighScoresModel;
}

...

@end

希望这会有所帮助!

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.

  1. Where should this model be created? In the AppDelegate? In the first view controller?
  2. 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!

这篇关于从视图控制器访问模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆