I have a problem with my timer not running repeatedly. I’m still new to coding for the iOS but from what I have gathered on this website and answers to other questions, it should work. Basically the timer should start updating when the timerStart button is pressed and it should stop when the timerStop button is pressed.
Heres the sample code
.h file
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface PGSecondViewController : UIViewController <CLLocationManagerDelegate>
{
NSTimer *Timer;
IBOutlet UILabel *displayTimer;
int ticks;
}
@property (nonatomic, retain) IBOutlet UILabel *displayTimer;
-(IBAction)timerStart:(id)sender;
-(IBAction)timerStop:(id)sender;
-(void)updateTimer:(NSTimer *)theTimer;
@end
and heres the .m file
#import "PGSecondViewController.h"
@interface PGSecondViewController ()
@end
@implementation PGSecondViewController
@synthesize displayTimer;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UITabBarItem *tbi = [self tabBarItem];
[tbi setTitle:@"Start"];
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[displayTimer setText:@"00:00:00"];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)timerStart:(id)sender;
{
Timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
}
-(IBAction)timerStop:(id)sender;
{
[Timer invalidate];
Timer = nil;
}
-(void)updateTimer:(NSTimer *)theTimer
{
if (ticks == nil)
{
ticks = 0;
}
else
{
ticks = ticks + 1;
}
[displayTimer setText:[NSString stringWithFormat:@" %d ", ticks]];
}
@end
Basically what I get is the timer starting once and NSLabel displays 0 but after that nothing happens. I have tried it with [[NSRunLoop currentRunLoop] addTimer:Timer forMode:NSDefaultRunLoopMode] and [[NSRunLoop currentRunLoop] run] after scheduling the timer but it doesn’t help.
Any ideas??
Your if(ticks == nil) is broken; ticks is an int, not an object. Its initial value will be 0.
I just fixed by changing that method a bit, and everything works fine.