NSTimer无效时不会停止 [英] NSTimer Not Stopping When Invalidated
问题描述
.h文件中包含以下代码:
I have the following code in my .h file:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <AVFoundation/AVFoundation.h>
#import <MapKit/MapKit.h>
@interface LandingController : UIViewController<CLLocationManagerDelegate> {
CLLocationManager *LocationManager;
AVAudioPlayer *audioPlayer;
}
@property (nonatomic, retain) NSTimer *messageTimer;
- (IBAction)LoginButton:(id)sender;
@end
.m文件中包含以下代码:
I have the following code in my .m file:
@interface LandingController ()
@end
@implementation LandingController
@synthesize messageTimer;
- (void)checkForMessages
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"BINGO:"
message:@"Bingo This Works"
delegate:nil
cancelButtonTitle:@"Okay"
otherButtonTitles:nil];
[alert show];
}
- (IBAction)LoginButton:(id)sender {
if ([UserType isEqualToString:@"Owner"]) {
if (messageTimer){
[self.messageTimer invalidate];
self.messageTimer = nil;
}
} else {
if (!messageTimer){
self.messageTimer = [NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(checkForMessages)
userInfo:nil
repeats:YES];
}
}
}
@end
但是当我调用无效时,我的计时器不想停止.
But my timer doesn't want to stop when I call the invalidate.
仅两次按下LoginButton,一次,当strResult = ="Guard"时,然后应用程序将其更改为等于"Owner",并且用户再次按下登录按钮,因此我认为我不会m设置多个计时器.
The LoginButton is only pressed twice, once when the strResult is = to "Guard" and then the application changes it to be equal to "Owner" and the user presses the login button again, so I don't think I'm setting multiple timers.
按下登录按钮并启动计时器后,我选择了另一个视图,然后再次返回以再次按下登录按钮,这是我希望计时器停止的时间.因为我先切换视图然后又回来,我是否需要做一些特殊的事情来获取messageTimer?
After pressing the login button and starting the timer I segue to another view and then segue back to press the login button once more which is when I want the timer to stop. Do I need to do anything special to get the messageTimer since I switched views for a moment and then came back?
有什么想法吗?
谢谢!
推荐答案
您需要在创建计时器的同一线程上调用[self.messageTimer invalidate]
.只需确保计时器已在主线程上创建并失效即可.
You need to call [self.messageTimer invalidate]
on the same thread on which you created the timer. Just make sure that the timer is created and invalidated on main thread.
dispatch_async(dispatch_get_main_queue(), ^{
if ([UserType isEqualToString:@"Owner"]) {
[self.messageTimer invalidate];
self.messageTimer = nil;
} else {
self.messageTimer = [NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(checkForMessages)
userInfo:nil
repeats:YES];
}
});
这篇关于NSTimer无效时不会停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!