IOS - Objective C - 如何在退出视图时停止执行周期性功能?
问题描述:
我在我的一个viewControllers中有一个函数,每10秒执行一次。IOS - Objective C - 如何在退出视图时停止执行周期性功能?
我希望此功能在我退出视图时停止它的执行。
我想这和平的代码:
-(void)viewWillDisappear:(BOOL)animated
{
NSError *error2;
if ([_managedObjectContext save:&error2] == NO) {
NSAssert(NO, @"Save should not fail\n%@", [error2 localizedDescription]);
abort();
}
else
NSLog(@"Context Saved");
[self stopTimer];
NSLog(@"View will disappear now");
}
据basicly调用方法stopTimer会给null值的计时器。
- (void) stopTimer
{
[timer invalidate];
timer = nil;
}
我的问题是即使我离开我的视图,我的函数仍然执行。并永不停止。我怎样才能解决这个问题?
编辑:
这是我的NSTimer调用的函数:
- (void) MyFunctionCalledByNSTimer
{
[timer invalidate];
timer = [NSTimer scheduledTimerWithTimeInterval:10.0f
target:self selector:@selector(Function1) userInfo:nil repeats:YES];
}
我宣布我的NSTimer在我的viewController
NSTimer *timer;
的.M如果您需要更多撕成小块的代码只是问,我会编辑问题。
答
使用此代码 通话stopTimer在主线程
-(void)viewWillDisappear:(BOOL)animated
{
NSError *error2;
if ([_managedObjectContext save:&error2] == NO) {
NSAssert(NO, @"Save should not fail\n%@", [error2 localizedDescription]);
abort();
}
else
NSLog(@"Context Saved");
dispatch_async(dispatch_get_main_queue(), ^{
//Your main thread code goes in here
[self stopTimer];
});
NSLog(@"View will disappear now");
}
记住,你必须在其上安装了定时器线程发送无效消息。如果您从另一个线程发送此消息,则与定时器关联的输入源可能不会从其运行循环中删除,这可能会阻止线程正常退出。
答
可能会因为创建多个计时器而发生问题,并且仅使您参考的内容失效。
因此,可修改MyFunctionCalledByNSTimer
像下面将解决您的问题:
- (void) MyFunctionCalledByNSTimer
{
if(!timer){
timer = [NSTimer scheduledTimerWithTimeInterval:10.0f
target:self selector:@selector(Function1) userInfo:nil repeats:YES];
}
}
现在,只有一个计时器参考将在那里和[timer invalidate]
会作废计时器。
'1)'您的'viewWillDisappear:'不会编译,因为它缺少'}' - 请添加完整,正确的方法。 '2)'你不是在调用'[super viewWillDisappear:animated];' - 请将其添加到你的方法中。 '3)'请添加由计时器调用的函数,该函数经常运行到该问题。 '4)'请添加声明定时器的代码以及它将运行的方法。 –
请问您可以添加创建nstimer的代码或创建nstimer的代码? –
@RoboticCat我们不需要调用super viewWillDisappear,除非我们想重写它。即使我们没有调用super,该方法也会被调用! –