Following is my sample code.
@interface TrackTimer : NSObject {
NSTimer *timer;
}
@property (nonatomic, retain) NSTimer *t开发者_运维知识库imer;
- (void) startTimer;
- (void) stopTimer;
- (void) timerFired;
@end
TrackTimer.m
@synthesize timer;
- (void) startTimer
{
NSLog(@"Timer started ...");
if(timer)
{
timer = nil;
}
timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timerFired) userInfo:nil repeats:NO];
}
- (void) stopTimer
{
NSLog(@"Timer stoped ...");
[tTimer invalidate];
}
- (void) timerFired
{
NSLog(@"Timer Fired ... :)");
}
I have to use the same timer object from 3 different view controllers, my problem is startTimer
method do not invoke timerFired
method in 2nd UIViewController. Its works perfectly on 1st and 3rd View Controller.
appln Flow : 1stView -> 2ndView -> 3rdView
You are doing everything right... almost. Your timer does not fire, because of the "if" statement.
if (timer) {
timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(boom) userInfo:nil repeats:NO];
}
Here, the "if" statement returns NO, because the timer is not yet initialized.. The fact that you make it a property and synthesize it does not mean that (timer != nil)
If you remove the "if" statement it should work...
From the Apple docs on NSTimer:
The message to send to target when the timer fires. The selector must have the following signature:
- (void)timerFireMethod:(NSTimer*)theTimer
So, it looks like the signature of your timerFired method needs to be expanded to include one parameter '(NSTimer*)theTimer' and your selector needs to be @selector(timerFired:)
Don't really know how you do that, but NStimer has a class method called + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats. So you can do it like this:
timer=[NSTimer scheduledTimerWithTimeInterval:2 target:self
selector:@selector(timerFired)
userInfo:nil
repeats:YES];
This will invoke the timerFired method for you.
P.S.Here's the link to a simple app that does just what you want.
http://www.mediafire.com/?8uz115drqzb2nan
精彩评论