0

谁能告诉我如何保存 NSTimer ?我需要显示玩家完成游戏的时间。请建议。

谢谢。

4

4 回答 4

5

你不需要使用NSTimer. 我建议你使用NSDate

游戏开始时:

startDate = [NSDate date];

游戏结束时:

endDate = [NSDate date];
NSTimeInterval interval = [endDate timeIntervalSinceDate:startDate];

所以现在你有时间了,可以随心所欲地使用它。NSUserDefaults您可以像普通double值一样保存它

于 2012-12-04T09:43:00.143 回答
2

你可以这样做..

int currentTime;

BOOL isGameOver;

 - (void)viewWillAppear:(BOOL)animated 
    {
       isGameOver=FALSE;
       [self start];
       [super viewWillAppear:YES];
    }

- (IBAction)start{

    currentTime = 0;// SET 60 SECODE AS STATICULLY YOU CAN SET YOUR OWN TIME
    lbl=[[UILabel alloc]init];
    //creates and fires timer every second
    myTimer = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES]retain];
}

-(IBAction)gameOverAction
{
    isGameOver=TRUE;

//your game action Whenever its game over this method fire and Set One Bool value in this method like
}

-(void)showTime{



        if(isGameOver==TRUE)
        {

            [myTimer invalidate];
            myTimer = nil;
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Over"
                                                            message:[NSString stringWithFormat:@"Your Rount Time is %.2d", currentTime]
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];

        //you can save this [NSString stringWithFormat:@"Your Rount Time is %.2d", currentTime] in nsuserdefoult or database like bellow

          NSString *myGameLastTime =[NSString stringWithFormat:@"Your Rount Time is %.2d", currentTime] ;
          NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
          [defaults setObject:myGameLastTime forKey:@"gameoverTime"];

          [defaults synchronize];

         //now you can get this time anyplace in your project like [[NSUserDefaults standardUserDefaults] valueForKey:@"gameoverTime"]


        }

        currentTime++;
        lbl.text = [NSString stringWithFormat:@"%.2d", currentTime];

    NSLog(@"my lable == %@",lbl.text);


}

希望它能帮助你一切顺利

于 2012-12-04T09:54:06.780 回答
0

你应该在问这些问题之前做一些研究,用谷歌很容易弄清楚,最多需要 20 分钟,

NSUserDefaults *YourTimerName=[NSUserDefaults standardUserDefaults];
[defaultsPassword setObject:YourTimerName forKey:@"key1"];
[defaultsPassword synchronize];

然后你可以像这样恢复它

Nsstring *str=[[NSUserDefaults standardUserDefaults]objectForKey:@"key1"];

但是你需要先把你的定时器 Nsstring 格式化然后保存

于 2012-12-04T09:50:43.670 回答
-1

NSTimer只是周期性时间事件的来源,没有太多可保存的。如果您使用它来记录游戏中的时间,则必须有一个变量来记录总时间。将其保存到NSUserDefaults或某处。

于 2012-12-04T09:39:21.873 回答