我如何拥有一个每秒更改一次标签的计时器? Xcode 6

时间:2015-02-23 00:51:59

标签: ios objective-c xcode sprite-kit xcode6

我做了一个NSTimer,我让它每秒都运行一个方法,它有一个每次加一个的整数并放入SKLabelNode但它永远不会改变。这是代码。 (对不起,如果我把它搞糊涂了)

> #import "GameScene.h"
> 
> @implementation GameScene
> 
> -(void)didMoveToView:(SKView *)view {
>     /* Setup your scene here */
>     
>     [NSTimer timerWithTimeInterval:1
>                                     target:self
>                                     selector:@selector(timerMethod)
>                                     userInfo:nil
>                                     repeats:YES];
>     
>     timeAlive = [SKLabelNode labelNodeWithFontNamed:@"Arial"];
>     timeAlive.text = @"Time Alive: 0 Seconds";
>     timeAlive.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
>     
>     character = [SKSpriteNode spriteNodeWithImageNamed:@"Character"];
>     character.position = CGPointMake(CGRectGetMidX(self.frame)/2 - 150, CGRectGetMidY(self.frame)/2);
>     
>     enemy = [SKSpriteNode spriteNodeWithImageNamed:@"Character"];
>     enemy.name = @"enemy";
>     enemy.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)/2);
>     
>     [self addChild:timeAlive];
>     
>     [self addChild:character];
>     [self addChild:enemy];
>      }
> 
> -(void) timerMethod{
>     
>     timeAlive.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
>     timeAliveString = [NSString stringWithFormat:@"Time Alive: %d Seconds", timeAliveInt];
>     //timeAliveString = [@(timeAliveInt) stringValue];
>     timeAlive.text = timeAliveString;
>     timeAliveInt = 1;
>      }
> 
> -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
>     /* Called when a touch begins */
>     
>     for (UITouch *touch in touches) {
>         CGPoint location = [touch locationInNode:self];
>         
>         
>         
>     } }
> 
> -(void)update:(CFTimeInterval)currentTime {
>     /* Called before each frame is rendered */ }
> 
> @end

(我在Header类中定义了变量)

2 个答案:

答案 0 :(得分:1)

不要在SpriteKit中使用NSTimer。它们与SpriteKit不兼容。例如,在设置paused的{​​{1}}属性时,不会自动暂停NSTimer。你可以改为SKActions。

SKScene

答案 1 :(得分:-1)

您希望scheduledTimerWithInterval代替timerWithTimeInterval。这一点,以及保留对您创建的计时器的引用,应该可以解决您的问题。