我是iOS新手,在我的项目中,我将NSTimer与导航控制器一起使用。我在我的项目中使用了两个类,第一类是ViewController,第二类是PlayTheme。ViewController和PlayTheme类与segue连接。在PlayTheme类中,我使用NSTimer和"FiredTimer方法"调用每10毫秒一次。PlayTheme Class的源代码为:以下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;
}
}
两种方法都有效,但当我按照以下步骤操作时,计时器不会停止:
- 我在PlayTheme课堂和StartTime
- 返回ViewController
- 回到游戏主题课
- 和StopTimer方法调用,方法调用但不停止计时器
给我解决问题的建议,并告诉我NSTimer如何在BackGround中使用NSTimer在特定时间内播放声音?
高级感谢。
有几种解决方案可用于解决您的问题:
- 不鼓励-全局存储对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
你能告诉我你是如何添加计时器的吗?
应该是这样的-
[[NSRunLoop mainRunLoop]addTimer:模式计时器:NSRunLoopCommonModes];
创建一个后台计时器子类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]]);
}
@结束
退出PlayTheme视图控制器时,将丢失对计时器的引用。如果你想保留对计时器的引用,你需要将计时器存储在"全局"的某个地方。如何以及在哪里存储取决于你的应用程序的结构。
编辑
澄清一下:我不建议使用全局变量!我写这篇文章只是为了表明一个变量"存在"在更多的地方,而不仅仅是一个控制器。查看@sweepy_的答案以了解可能的解决方案。