NSTimer不会停止使用导航控制器

时间:2015-03-23 11:43:52

标签: ios objective-c nstimer avaudioplayer navigationcontroller

我是iOS新手, 在我的项目中,我使用NSTimer和导航控制器。 我在项目中使用了两个Classes, 第1类是ViewController,第2类是PlayTheme。 ViewController和PlayTheme类与segue连接。 在PlayTheme Class中,我每10毫秒使用NSTimer和“FiredTimer方法”调用。 PlayTheme类的源代码是: 下面的NSTimer启动方法

- (IBAction)startTimerMethod:(id)sender
{
    UIBackgroundTaskIdentifier bgTask =0;
        UIApplication  *app = [UIApplication sharedApplication];
        bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
            [app endBackgroundTask:bgTask];
        }];

    timer = [NSTimer
             scheduledTimerWithTimeInterval:0.01
             target:self
             selector:@selector(timerFired:)
             userInfo:nil
             repeats:YES];
}

以下方法是停止计时器

- (IBAction)stopTimerMethod:(id)sender
{
    if([timer isValid])
    {
        [timer invalidate];
        timer=Nil;
    }
}

两种方法都有效,但当我按照以下步骤操作时,计时器不会停止:

  1. 我在PlayTheme Class和StartTime
  2. 返回ViewController
  3. 回到PlayTheme Class
  4. 和StopTimer方法调用,方法调用但不会停止计时器
  5. 给我建议解决我的问题,并告诉我NSTimer如何在BackGround中使用NSTimer在特定时间播放声音?

    先谢谢你。

4 个答案:

答案 0 :(得分:0)

退出PlayTheme视图控制器时,将丢失对计时器的引用。您需要将计时器存储在全球某个地方'如果你想保留对它的引用。如何以及在何处执行此操作取决于应用程序的结构。

修改

要清理:我不建议使用全局变量!我只是写了这个来表示一个存在的变量'在更多的地方,然后只有一个控制器。检查@sweepy _的答案以获得可能的解决方案。

答案 1 :(得分:0)

你能告诉你如何添加计时器吗?

应该是这样的 -

[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

答案 2 :(得分:0)

有几种解决方案可以解决您的问题:

  • 气馁 - 全局存储对NSTimer实例的引用(查看Singleton设计模式)
  • 推荐 - 从第一个视图控制器实例化您的计时器,以便始终对其进行引用,并最终将其传递到目标PlayTheme视图控制器。

请记住,如果您必须与多个实例共享元素,则此元素必须由所有这些实例的第一个公共父管理。

 VC1 -> VC2 -> VC3
 VC1 -> VC5
 // In such a case, if both VC3 and VC5 need to share an element,
 // this one must be managed by VC1

答案 3 :(得分:0)

创建后台计时器子类NSOperation并创建它的实例。另外,为了使计时器在特定时间内保持活动状态,您需要指定当前时间+持续时间的日期,如下所示 -

#import <Foundation/Foundation.h>

@interface BackgroundTimer : NSOperation
{
    BOOL _done;
}
@end



#import "BackgroundTimer.h"

@implementation BackgroundTimer

-(void) main
{
    if ([self isCancelled])
    {
        return;
    }

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:30
                                             target:self
                                           selector:@selector(timerFired)
                                           userInfo:nil
                                            repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

    //keep the runloop going as long as needed
    while (!_done && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                              beforeDate:[NSDate dateTillTheSpecificTime]]);

}

@end