我有NSTimer
需要在後臺運行,因爲你瀏覽到不同的頁面,但是當我在視圖控制器文件中找到它時,id會移動到另一個頁面,破壞計時器。所以我做了一個單例類,並試圖將代碼放在那裏,然後從那裏調用它。此時代碼將運行,但當我導航到另一頁時,它不會繼續運行計時器。任何想法都非常感謝,請索取更多信息!在singleton類中運行NSTimer
代碼: 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;
}
在你的'instance'類方法中,你永遠不會到達Synchronized塊的末尾,返回必須在synchronized塊之外。 – lucaslt89
目前尚不清楚你正在使用什麼代碼。你說過你在單例中試過,但是你發佈的代碼在視圖控制器中顯示了定時器。 – rdelmar
@ lucaslt89你能解釋一切嗎?我不明白同步塊或哪個文件? .m或.h – Gosell1