且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从视图控制器访问模型?

更新时间:2023-10-25 23:49:22

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!