2013-12-18 80 views
-2

我想在兩個場景之間傳遞數據(分數)。但是,我的第二個場景是在第一個場景可以傳遞數據之前分配的。不知道爲什麼。我的代碼:傳入的場景在當前場景可以傳遞數據之前分配

MainScreen.m

-(void)gameOver 
{ 

    self.view.scene.userData = [[NSMutableDictionary alloc]init]; 
    [self.view.scene.userData setObject:self.score forKey:@"score"]; 

    SVGGameOverScreen *gameOverScreen = [[SVGGameOverScreen alloc]initWithSize:self.size]; 
    gameOverScreen.view.scene.userData = [[NSMutableDictionary alloc]init]; 
    [gameOverScreen.userData setObject:[self.view.scene.userData objectForKey:@"score"] forKey:@"score"]; 

    NSLog(@"Value of score (FIRST SCREEN): %d", self.score.intValue); 
    NSLog(@"Value of object for score key (FIRST SCREEN) %@", [self.userData objectForKey:@"score"]); 

    [self.backgroundMusicPlayer stop]; 

    //Transition to new view 
    SKTransition *transition = [SKTransition pushWithDirection:SKTransitionDirectionUp duration:1.0]; 
    transition.pausesOutgoingScene = YES; 
    [self.view presentScene:gameOverScreen transition:transition]; 
} 

GameOverScreen.m

in init method 
... 
self.score = [[NSNumber alloc]init]; 
     self.score = [self.userData objectForKey:@"score"]; 
     NSLog(@"Value of object for score key (SECOND SCREEN) %@", [self.userData objectForKey:@"score"]); 

輸出如下GAMEOVER時被調用:

2013-12-18 15:47:48.646 [] Value of object for score key (SECOND SCREEN) (null) 
2013-12-18 15:47:48.700 [] Value of score (FIRST SCREEN): 26 
2013-12-18 15:47:48.700 [] Value of object for score key (FIRST SCREEN) 26 

回答

1

如果你打電話

[SVGGameOverScreen alloc]initWithSize:self.size]; 

並且不要在其中設置userData,當然它不會被設置,直到方法返回。無論是寫抄錄你需要做的用戶數據被設置後,任何邏輯的新方法,它具有這樣的

initWithSize: (CGSize) size userData: (NSMutableDictionary*) userData 

的新方法傳遞到遊戲結束畫面,並將其設置裏面,或(可能更好)使自定義設置爲財產,並把邏輯在那裏。

順便說一句,爲什麼你創建一個NSNumber的分數只設置它等於值userData的「分數」鍵?

+0

對於您關心的NSNumber,您會有什麼建議? – EvilAegis

+0

完全擺脫那條線。沒有必要初始化一個新的NSNumber,以便將分數設置爲等於下一行中的其他值。 –

相關問題