【问题标题】:NSTimer in Objective C when Click on Home Button单击主页按钮时,Objective C中的NSTimer
【发布时间】:2012-05-30 04:32:32
【问题描述】:

我在 ViewController 类中有 NSTimer.. 并且 NStimer 的所有方法都在该类中.. 我的 NSTimer 可以正常工作以进行播放和暂停...当我按下 iPhone 上的主页按钮时,计时器也正常工作(它从应用程序进入前台时应用程序进入后台的时间开始运行...当警报出现在屏幕上时,我的 NSTimer 正在运行(没有对警报做出响应)。我想停止 NSTimer 直到用户响应我的警报...之后我想启动 NSTimer...如何我可以这样做吗...?请帮助我...在此先感谢...我想从 Appdelegate.m 文件中调用 NSTimer 方法...我正在正确调用这些方法...并且调用了 ViewController 中的方法...但是该操作未执行。 .. 对于从 viewController 类调用时相同的方法,它正在工作......

enter code here

ViewController.h

+(ExamViewController *)evcInstance;

ViewController.m

ExamViewController *evc = nil;
@implementation ExamViewController

+(ExamViewController *)evcInstance
{
if(!evc) 
{
    evc = [[ExamViewController alloc] init];
}
return evc;
}




- (void)onStartPressed
{
stopwatchtimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:stopwatchtimer forMode:NSRunLoopCommonModes]; 
resume.hidden = YES;
resume.enabled=NO;
pause.hidden = NO;
pause.enabled=YES;
} 


- (void)onStopPressed
{


[stopwatchtimer invalidate];
stopwatchtimer = nil;
pause.hidden = YES;
pause.enabled=NO;
resume.hidden = NO;
resume.enabled=YES;
}

Appdelegate.m

- (void)applicationWillEnterForeground:(UIApplication *)application
{
[[ExamViewController evcInstance] onStopPressed];

NSLog(@"applicationWillEnterForeground");

if(viewCalled ==YES)
{

    UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"" message:@"DO! You Want To continue" delegate:self cancelButtonTitle:@"YES" otherButtonTitles:@"NO", nil];

    [alertview show];

    [alertview release];



}
/*
 Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
 */
}

【问题讨论】:

  • 我已经编辑了我的问题.. 请看一次
  • 请附上适用的代码,以便我们提供帮助!
  • 我已包含代码..请检查一次..
  • 是的...这里并不需要代码。使用 danh 指出的 UIAlertView 委托方法。

标签: iphone objective-c ios5 nstimer


【解决方案1】:

一些事情:

1) 它看起来像一个不完整的单例设计。如果你真的想要一个单例,请参考帖子like this one

2) 无需在当前运行循环中添加秒表计时器。 scheduleTimerWithTimeInterval 方法会为您安排。

3) 我看不到您在哪里声明秒表计时器,但请务必将其声明为保留属性(或 ARC 中的强属性)。

4) 要停止计时器,只需调用[stopwatchtimer invalidate]; 要重新启动它,请使用您最初调用的相同的 scheduleTimerWithTimeInterval 类方法重新实例化并覆盖旧的。

5) 要在警报视图完成时执行任何操作,请实现委托方法:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

因此,您可以在显示警报之前使计时器无效,然后在收到警报完成通知时重建它。

【讨论】:

  • 我没有看到您在发布的代码中停止了它。在 [alert show] 之前,您需要调用无效或“onStopPressed”。尝试在演出前在线执行此操作。它会停止。如果你仍然看到它开火,这意味着你有两个或更多的计时器。在构建它的位置设置断点。您应该只命中该断点一次。祝你好运。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多