在视图被解除之前不断调用方法

时间:2015-12-12 08:40:06

标签: ios objective-c

我有一个在用户完成游戏时加载的endGame视图。它以模态方式呈现在游戏视图的顶部。在viewDidLoad中,我正在调用一种方法来保存数据,例如分数以及他们玩过的特定游戏模式的数量。该方法被多次调用 - 大约每秒一次,但它是不规则的。

结束游戏屏幕:

#import "endGameScreen.h"
#import "ViewController.h"
#import "GameData.h"

@implementation endGameScreen

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)awakeFromNib {
    [self getAchievementData];
}

- (void)getAchievementData {
    [RWGameData sharedGameData].timedPlayed++;
    NSLog(@"Timed played: %ld", [RWGameData sharedGameData].timedPlayed);
}

- (void)writeAchievementforKey:(NSString *)achKey {
    [data setObject:[NSNumber numberWithInteger:1] forKey:achKey];
    [data writeToFile: path atomically:YES];
}

我正在加载endGameScreen类,如下所示: 的 GameViewController.m

- (void)viewDidLoad {
    if (self.gameMode == 1) {
        self.gridSize = 3;
        secondsLeft = 10;
        [self countdownTimer];
    }
}

-(void)countdownTimer {
    secondsLeft = minutes = seconds = 0;
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
}

// Timer in the game going to zero
- (void)updateCounter:(NSTimer *)theTimer {
    if (secondsLeft > 0 ){
        secondsLeft -- ;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
        timePlayedLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
        if (secondsLeft == 1) {
            //Call endGame method
            timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                             target:self
                                           selector:@selector(endGame)
                                           userInfo:nil
                                            repeats:NO];
        }
    }
    else {
        secondsLeft = 10;
    }
}

- (void)endGame {
    [timer invalidate];
    [self saveScores];

    //Segue in the storyboard
    [self performSegueWithIdentifier:@"endGame" sender:self];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@"endGame"]) {
        endGameScreen *vc = [segue destinationViewController];
        if (self.gameMode == 1) {
            vc.gameMode = 1;
        }
        else {
            vc.gameMode = 2;
        }
    }
}

我收到的NSLog消息不断增加说“模式一播放:27”,“模式一播放:28”,“模式一播放:29”,等等。

1 个答案:

答案 0 :(得分:1)

您的-endGame方法并不会使您认为的计时器无效。

-updateCounter:使用新的一次性定时器覆盖timer实例变量以调用-endGame,但这并不会停止另一个定时器,即{ {1}}。该计时器继续发出,呼叫-countdownTimer,这会不断创建更多的一次性计时器来呼叫-updateCounter:。所以,这会被反复调用。