我已经启动了一个计时器,在10秒后调用一个方法。计时器从didFinishLaunchingWithOptions开始。它工作正常,但我想在注销时从另一个UISubclass停止该计时器。我怎么能这样做我的代码是
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[NSThread sleepForTimeInterval:2.0];
[self.window addSubview:viewController.view];
[self setupTimer];
[self.window makeKeyAndVisible];
return YES;
}
-(void)setupTimer;
{
timer = [NSTimer timerWithTimeInterval:10
target:self
selector:@selector(triggerTimer:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void)triggerTimer:(NSTimer*)timer;
{
NSLog(@"===============this method is call after every 10 second===========================");
Getlocation *object=[[Getlocation alloc] init];
[object updatelocation];
}
-(void)stopTimer:(NSTimer*)timer;
{
[timer invalidate];
timer=nil;
}
答案 0 :(得分:0)
if([timer isValid])
[timer invalidate];
timer = nil;
答案 1 :(得分:0)
以NSTimer为对象 将此行写在您想要调用方法
的位置timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(NEWTIMER) userInfo:nil repeats:YES];
将此代码写在那里你想要停止计时器。
[timer invalidate];
timer = nil;
[timer release];
如果您想在应用程序出现后台时停止计时器。您应该将此代码写入此方法。
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[timer invalidate];
timer = nil;
[timer release];
}
答案 2 :(得分:0)
在注销ButtonAction方法中编写代码。
- (IBAction)LogOutButtonPressed:(id)sender {
[计时器无效]; timer = nil; [计时器发布];
}