2015-12-23 143 views
1

我想将我的游戏部分的分数传递给记分板。但是,我似乎无法做到这一点。这是我的代码,在我的GameViewController无法在两个视图控制器之间传递数据

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

这是我的代码在我的ScoreViewController

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

在日志中它显示正确的分数,然后它执行segue。但是,一旦在ScoreViewController它给出一个空值。我提到Passing Data between View Controllers但它不适合我。为什么它不适合我?代码有什么问题,或者我错过了代码中的某些内容?

回答

0

您可以在preparsforsegue方法下值传递像下面,

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

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

     destViewController .score = scoreAsString; 
    } 

} 

它会奏效。尝试一下! 注: 你应该在接口定义变量一样,

ScoreViewController *scoreVC; 
+1

使用segue.destinationViewController可能会更好。 – Lucifron

0

你可以试试这个。

导入SecondViewController向您GameViewController

#import "SecondViewController.h" 

然后在GameViewController.m文件中使用这种方法

- (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) 
    } 
} 

检查你给一个您SEGUE,并确保您已使用相同名称为segue.identifier

0

目标视图控制器中的自定义init ...方法,它将视图控制器需要的数据作为参数。这使得类的目的更加清晰,并避免了当视图已经在屏幕上时另一个对象为属性分配新值时可能出现的问题。在代码中,这应该是这样的:

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

而且在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; 
} 
相关问题