有一个带有objective-c的已创建的nstimer对象。它的工作正常,而应用程序是手机的背景,但当我回到以前的viewcontroller时,一切都在重置。
更新:
@property NSTimer * timer;
-(void)starter{
if ([_timer isValid]) {
[_timer invalidate];
[_startStopBtn setTitle:@"START" forState:UIControlStateNormal];
}
else{
_timer = [NSTimer scheduledTimerWithTimeInterval: 1.0
target: self
selector:@selector(increaseSecond)
userInfo: nil repeats:YES];
[_startStopBtn setTitle:@"END WORKOUT" forState:UIControlStateNormal];
}
}
- (无效)increaseSecond {
[self checkOtherSecond];
- (无效)checkOtherSecond {
[self increaseMinute];
}
这是计时器的代码。计算秒数,分钟数和以后数小时数。
我需要为AppDelegate创建计时器对象,但是呢?
答案 0 :(得分:1)
也许你可以尝试创建一个单例计时器:
@interface singletonTimers : NSObject
+(instancetype)shareSingletonTimers;
-(void)setTimes:(int)times;
-(void)startTimer;
-(void)stopTimer;
@end
@implementation singletonTimers
static singletonTimers *_instance;
+ (id)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
+ (instancetype) shareSingletonTimers
{
if (_instance == nil) {
_instance = [[singletonTimers alloc] init];
}
return _instance;
}
-(void)setTimes:(int)times{
}
-(void)startTimer{
}
-(void)stopTimer{
}
@end
如果您创建一个单例计时器,它将在应用程序生命周期中保持活动状态 希望它有所帮助。
答案 1 :(得分:0)
试试这个。
在AppDelegate.h中添加URLClassLoader
和NSTimer
的属性它将如下所示
<强> AppDelegate.h 强>
declare methods
在 AppDelegate.m
中@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic) NSTimer *timer;
- (void) startTimer;
- (void) stopTimer;
@end
现在在您的视图控制器中,您的START和STOP按钮方法将在那里。修改它们如下。
<强> ViewController.m 强>
- (void) startTimer {
_timer = [NSTimer scheduledTimerWithTimeInterval: 1.0
target: self
selector:@selector(increaseSecond)
userInfo: nil repeats:YES];
}
- (void) stopTimer {
if ([_timer isValid]) {
[_timer invalidate];
}
}
- (void)increaseSecond {
[self checkOtherSecond];
}
-(void)checkOtherSecond {
NSLog(@"Method Called on each second.");
}
当您完成此过程并将方法绑定到ViewController中的相应按钮时,您会看到将显示我们放入- (IBAction)btnStartClick:(id)sender {
AppDelegate *objDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[objDelegate startTimer];
}
- (IBAction)btnStopClick:(id)sender {
AppDelegate *objDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[objDelegate stopTimer];
}
方法的常量日志。