传入场景在当前场景可以传递数据之前分配

时间:2013-12-18 23:50:25

标签: iphone objective-c sprite-kit

我正在尝试在两个场景之间传递数据(得分)。但是,我的第二个场景是在第一个场景可以传递数据之前分配。不知道为什么。我的代码:

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 个答案:

答案 0 :(得分:1)

如果你打电话

[SVGGameOverScreen alloc]initWithSize:self.size];

并且不要在其中设置userData,当然在方法返回之前不会设置它。要么设置一个新的方法来重现你在设置userData之后需要做的任何逻辑,用这样的新方法将它传递到游戏屏幕上

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

并将其设置为内部,或者(可能更好)为属性创建自定义setter并将逻辑放在那里。

顺便提一下,为什么你只为分数创建一个NSNumber来设置它等于值userData的“得分”键?