Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

objective c - Passing data between classes

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.

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.

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

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?

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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

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

if ([QuizModel instance].isMultiplayer)

or

[QuizModel instance].isMultiplayer = YES;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...