当您导航到不同的页面时,我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;
}