2015-12-23 222 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; 
} 
相關問題