1

I am trying to pass the score from my game part to the scoreboard. However, i cannot seem to do it. This is my code in my GameViewController.

- (void)gameHasEnded {
    ScoreViewController *scoreVC = [[ScoreViewController alloc] initWithNibName:@"ScoreVC" bundle:nil];
    scoreVC.score = scoreAsString;
    NSLog(@"%@",scoreVC.score);
    [self performSegueWithIdentifier:@"continueToScore" sender:self];
}

This is my code in my ScoreViewController.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scoreLabel.text = scoreString;
    NSLog(@"Score = %d", self.score);
}

In the log it shows the correct score before it performs the segue. However, once in the ScoreViewController it gives a null value. I referred to Passing Data between View Controllers but it did not work for me. Why does it not work for me? Is there something wrong with the code or did i miss out on something in the code?

Sujatha Girijala
  • 1,141
  • 8
  • 20
Chandran
  • 59
  • 8

3 Answers3

0

you can pass the values under the preparsforsegue method like below,

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    if([[segue identifier] isEqualToString:@"continueToScore"])
   {
       ScoreViewController *destViewController = segue.destinationViewController;

       destViewController .score = scoreAsString;
    }

}

it will work. try it! Note: you should define variable in interface like,

ScoreViewController *scoreVC;
Undo
  • 25,519
  • 37
  • 106
  • 129
S. Karthik
  • 618
  • 5
  • 16
0

you can try this.

import your SecondViewController to to your GameViewController

#import "SecondViewController.h"

then in your GameViewController.m file use this method

- (void)prepareForSegue:(UIStoryboard *)segue sender:(id)sender
{
  if([segue.identifier isEqualToString:@"your_segue_name_here"])
   {
      SecondViewController *svc = segue.destinationViewController;
      //herer you can pass your data(it is easy if you use a model)
   }
}

check you have given a name to your segue and , ensure that you have used same name as segue.identifier

Jobs
  • 269
  • 2
  • 6
  • 21
0

A custom init... method in the target view controller that takes the data the view controller needs as arguments. This makes the purpose of the class even clearer and does avoid possible problems when another object assign a new value to the property when the view is already on screen. In code, this would look like this:

  - (IBAction)nextScreenButtonTapped:(id)sender
{
ScoreViewController *scoreVC = [[ScoreViewController alloc]
initWithScore:self.scoreAsString];
[self.navigationController pushViewController:scoreVC animated:YES];
}

And in ScoreViewController.m:

 - (id)initWithScore:(NSString *)theScore
{
self = [super initWithNibName:@"ScoreViewController" bundle:nil];
if (self) {
_score = [theScore copy];
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
self.scoreLabel.text = _score;
}
Sujatha Girijala
  • 1,141
  • 8
  • 20