Mattias
Mattias

Reputation: 65

Retain UILabel value between random views

I'm making a view based quiz app for the iPhone where the player is going randomly between three different views when answering the questions. They get +1 when answering correct and -1 when tapping the wrong answer. But after answering the question, when you go to the new random view, I need the UILabel to show the score from the previous view. How do I do that?

Here is my code:

ViewController.h

@interface ViewController : UIViewController {

    IBOutlet UILabel *labelQuestion;
IBOutlet UILabel *labelAnswer1;
IBOutlet UILabel *labelAnswer2;
IBOutlet UILabel *labelAnswer3;
IBOutlet UILabel *labelScore;

int score;    

}

@property (nonatomic, retain) IBOutlet UILabel *labelScore;
@property (nonatomic) int score;


ViewController.m

@synthesize labelScore;
@synthesize score;

-(IBAction)CorrectAnswer; {

    score = score +1;
    labelScore.text = [NSString stringWithFormat:@"%i", score];

}

-(IBAction)WrongAnswer; {

    score = score -1;
    labelScore.text = [NSString stringWithFormat:@"%i", score];

}

Upvotes: 2

Views: 194

Answers (3)

Baby Groot
Baby Groot

Reputation: 4279

Make the variable score global i.e. define this in your AppDelegate and you can access it throughout your application.

Upvotes: 1

jrtc27
jrtc27

Reputation: 8526

As they're properties, when you create the next view you can set the label's text to the current view's text and the score to the current view's.

Upvotes: 1

Swapnil Luktuke
Swapnil Luktuke

Reputation: 10475

the quickest but dirty way is to store it in app delegate.. and if you want it to persist between app launches, store it in user defaults.. but as i said this is dirty..

Upvotes: 1

Related Questions