【发布时间】:2013-05-10 05:21:44
【问题描述】:
我的 .h 文件中有以下代码:
#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 文件中有以下代码:
@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
但是当我调用无效时,我的计时器不想停止。
LoginButton 只被按下了两次,一次当 strResult 为 =“Guard”,然后应用程序将其更改为等于“Owner”并且用户再次按下登录按钮,所以我不认为我' m 设置多个定时器。
在按下登录按钮并启动计时器后,我切换到另一个视图,然后再次切换到再次按下登录按钮,此时我希望计时器停止。我是否需要做任何特别的事情来获取 messageTimer ,因为我切换了一会儿视图然后又回来了?
有什么想法吗?
谢谢!
【问题讨论】:
-
你在哪里写了 scheduleTimerWithTimeInterval 代码?检查一下,即使您将其无效,它也必须再次初始化。
-
我把它写在一个 if 循环中,这个循环在应用程序中只发生一次,所以我认为它不会被重新初始化。
-
我添加了更多代码 - 见上文
-
能否在将 self.messageTimer 设置为 nil 之前检查 [self.messageTimer isValid] 的值是否为 NO?
-
刚刚添加了更多代码,类似的东西?
标签: objective-c nstimer