在类之间传递数据 [英] Passing data between classes

查看:103
本文介绍了在类之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个测验游戏,一切正常,但有一个我想改进的事情:
我的问题是,我有3个视图控制器。在第一个View控制器中,用户选择单人或多人模式。

I have developed a quiz game and everything works really well but there is a thing I want to improve: My problem is that I have 3 View Controllers. In the first View Controller the user selects single or multiplayer modus.

第二个ViewController是测验游戏。
但现在在第三个ViewController(结果屏幕)中,我需要知道用户是选择单人还是多人模式。

The second ViewController is the quiz game. But now in the third ViewController (the result screen) I need to know if the user chose single or multiplayer modus.

我不知道如何将此布尔值从ViewController 1传递到ViewController 3。

I don't know how to pass this boolean from ViewController 1 to ViewController 3.

此时,我在每个ViewController中都有一个布尔值,只是将此变量从View1传递给View2,然后传递给View3。但我不喜欢这个解决方案。有没有办法,我解决这与代表?

At the moment I have a boolean in every ViewController and just pass this variable from View1 to View2 and then to View3. But I don't like this solution. Is there a way that I solve this with delegates? Or do you know any other, better solution?

提前感谢

推荐答案

模型 - 视图 - 控制器方法表明布尔值属于应用程序的模型代码。将您的模型设为单身是一件常见的事情:

Model-View-Controller approach suggests that the boolean value belongs in the Model code of your application. It is a common thing to make your model a singleton:

QuizModel.h

QuizModel.h

@interface QuizModel : NSObject
@property (nonatomic, readwrite) BOOL isMultiplayer;
-(id)init;
+(QuizModel*)instance;
@end

QuizModel.m

QuizModel.m

static QuizModel* inst = nil;

@implementation QuizModel
@synthesize isMultiplayer;
-(id)init {
    if(self=[super init]) {
        self.isMultiplayer = NO;
    }
    return self;
}
+(QuizModel*)instance {
    if (!inst) inst = [[QuizModel alloc] init];
    return inst;
}
@end

现在可以在控制器代码中使用布尔:include QuizModel.h,然后写

Now you can use the boolean in your controller code: include "QuizModel.h", and write

if ([QuizModel instance].isMultiplayer)

[QuizModel instance].isMultiplayer = YES;

这篇关于在类之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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