当你导航到不同的页面时,我需要在后台运行NSTimer
,但是当我在视图控制器文件中有这个时,id会移动到另一个页面,它实际上会破坏计时器。所以我创建了一个单例类,并尝试将代码放在那里,然后从那里调用它。此时代码运行,但当我导航到另一个页面时,它不会继续运行计时器。非常感谢任何想法,请询问更多信息!
代码: Viewcontroller.h
#import <UIKit/UIKit.h>
#import "ApplicationManager.h"
@interface ViewController : UIViewController{
IBOutlet UILabel *time;
NSTimer *ticker;
}
- (IBAction)start;
- (IBAction)reset;
- (void)showActivity;
@end
//
// ViewController.m
// License
//
// Created by Connor Gosell on 7/2/13.
// Copyright (c) 2013 Connor Gosell. All rights reserved.
//
#import "ViewController.h"
#import "ApplicationManager.h"
@interface ViewController ()
@end
@implementation ViewController
-(IBAction) start
{
ticker:[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}
-(IBAction)reset
{
[ticker invalidate];
time.text = @" 0:00";
}
-(void) showActivity
{
int currentTime = [time.text intValue];
int newTime = currentTime + 1;
time.text = [NSString stringWithFormat:@"%d", newTime];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
/*-(IBAction) start
{
[[ApplicationManager instance] setTicker:[NSTimer scheduledTimerWithTimeInterval:1.0 target:self ``selector:@selector(showActivity) userInfo:nil repeats:YES]];
}
-(IBAction) reset
{
[[[ApplicationManager instance] ticker] invalidate];
time.text = @" 0:00";
}
-(void) showActivity
{
int currentTime = [time.text intValue];
int newTime = currentTime + 1;
time.text = [NSString stringWithFormat:@"%d", newTime];
}
*/
//
// ApplicationManager.h
// License
//
// Created by Connor Gosell on 7/31/13.
// Copyright (c) 2013 Connor Gosell. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ApplicationManager : NSObject{
}
+(ApplicationManager*) instance;
@end
//
// ApplicationManager.m
// License
//
// Created by Connor Gosell on 7/31/13.
// Copyright (c) 2013 Connor Gosell. All rights reserved.
//
#import "ApplicationManager.h"
@implementation ApplicationManager
static ApplicationManager* appMgr = nil;
+(ApplicationManager*) instance
{
@synchronized([ApplicationManager class])
{
if(!appMgr)
{
appMgr = [[self alloc] init];
}
return appMgr;
}
return nil;
}
+(id) alloc
{
@synchronized([ApplicationManager class])
{
NSAssert((appMgr == nil), @"Only one instance of singleton class may be instantiated.");
appMgr = [super alloc];
return appMgr;
}
}
-(id) init
{
if(!(self = [super init]))
{
[self release];
return nil;
}
return self;
}
答案 0 :(得分:0)
我会做一些假设,但你可以根据系统时间计算时间,而不是通过递增var。如果整个应用程序重用开始时间,则可以将其存储为应用程序委托中的属性。如果以这种方式计算时间,则可以在每个视图控制器出现时启动定时器并在消失时停止定时器,并且如果需要精确度,则可以从更快的间隔中受益。我在Pace Clock Mac和iOS应用程序中使用了类似的技术。
答案 1 :(得分:0)
将计时器放入AppDelegate,让计时器勾选发送通知,让视图控制器各自启用通知的监听器,以便他们可以进行更新。