显示在视图控制器之间保留的iOS应用程序的计时器

我一直试图通过使用NSTimer在我的应用程序的左下角显示一个计时器,并将“经过时间”显示为左下角的UILabel,但它并没有为我工作.
-(void)viewDidLoad
{
    NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aTime) userInfo:nil repeats:YES];
}

-(void)aTime
{
    NSLog(@"....Update Function Called....");

    static int i = 1;

    Label.text = [Nsstring stringWithFormat:@"%d",i];

    i++;
}

计时器实际上工作,但我不能让它由按钮触发.我正在尝试让计时器继续运行,而不是在进入下一个storyboard / xib文件时重新启动.

解决方法

要在按下按钮时实现计时器操作,您需要在IBAction方法上编写它,如:
- (IBAction) buttonPress
{
    NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aTime) userInfo:nil repeats:YES];
}

要存储以前的值,可以使用NSUserDefaultssqlite数据库.为此,我建议NSUserDefaults.

更改aTime方法,如:

-(void)aTime
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    id obj = [standardUserDefaults objectForKey:@"TimerValue"];
    int i = 0;

    if(obj != nil)
    {
        i = [obj intValue];
    }

    Label.text = [Nsstring stringWithFormat:@"%d",i];
    i++;

    [standardUserDefaults setobject:[NSNumber numberWithInt:i] forKey:@"TimerValue"];
    [standardUserDefaults synchronize];
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...