how to unschedule NSTimer in objective-c - iphone

I am using nested NSTimer in an application. I have two issues here.
How to re-initiate time counter in this function - (void)updateLeftTime:(NSTimer *)theTimer
How to kill previous timer because - (void)updateLevel:(NSTimer *)theTimer is also calling by timer.
- (void)viewDidLoad {
[super viewDidLoad];
tmLevel=[NSTimer scheduledTimerWithTimeInterval:20.0f target:self selector:#selector(updateLevel:) userInfo:nil repeats:YES];
tmLeftTime=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateLeftTime:) userInfo:nil repeats:YES];
}
- (void)updateLevel:(NSTimer *)theTimer {
static int count = 1;
count += 1;
lblLevel.text = [NSString stringWithFormat:#"%d", count];
tfLeftTime.text=[NSString stringWithFormat:#"%d",ANSWER_TIME];
tmLeftTime=[[NSTimer alloc] init];
tmLeftTime=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateLeftTime:) userInfo:nil repeats:YES];
[self playMusic];
}
- (void)updateLeftTime:(NSTimer *)theTimer {
static int timeCounter=1;
timeCounter+=1;
tfLeftTime.text=[NSString stringWithFormat:#"%d", (ANSWER_TIME-timeCounter)];
}

Use [tmLevel invalidate] to cancel schedule of a timer.
Don't forget to set tmLevel=nil immediately after (to avoid using the variable after the timer has been unscheduled and released by the Runloop)
Don't forget to invalidate the tmLevel timer before loosing the reference to it, namely call [tmLevel invalidate] also before assigning a new NSTimer to the tmLevel variable (or else the previous timer will continue to run in addition to the new one)
Note also that in your code you have useless allocations that are moreover creating a leak:
tmLeftTime=[[NSTimer alloc] init];
tmLeftTime=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateLeftTime:) userInfo:nil repeats:YES];
here you allocate an NSTimer instance, store this instance in tmLeftTime... and then immediately forget about this created instance to replace it with another one, created using [NSTimer scheduledTimerWithTimeInterval:...]!
Therefore, the NSTimer created using [[NSTimer alloc] init] is lost, and is creating a leak (as it will never be released).
Your first line is totally useless, it's kinda like you were doing
int x = 5;
x = 12; // of course the value "5" is lost, replaced by the new value

add the following lines when u want to reset the timer
[tmLeftTime invalidate];
tmLeftTime = nil;
you can also use
if ([tmLeftTime isValid]){
// the timer is valid and running, how about invalidating it
[tmLeftTime invalidate];
tmLeftTime = nil;
}

How about using only one timer instead of 3?
- (void)viewDidLoad {
[super viewDidLoad];
tmLeftTime=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateLeftTime:) userInfo:nil repeats:YES];
}
- (void)updateLevel {
static int count = 1;
count += 1;
lblLevel.text = [NSString stringWithFormat:#"%d", count];
tfLeftTime.text=[NSString stringWithFormat:#"%d",ANSWER_TIME];
[self playMusic];
}
- (void)updateLeftTime:(NSTimer *)theTimer {
static int timeCounter=1;
timeCounter+=1;
tfLeftTime.text=[NSString stringWithFormat:#"%d", (ANSWER_TIME-timeCounter)];
if (timeCounter >= ANSWER_TIME) {
timeCounter = 0;
[self updateLevel];
}
}

Invalidate your timer with the invalidate method in your updateLevel: method and re-schedule the same timer.
[tmLevel invalidate];
tmLevel = [NSTimer scheduledTimerWithTimeInterval:20.0f target:self selector:#selector(updateLevel:) userInfo:nil repeats:YES];
And if you wanna call the updateTimeLeft: method you don't need to alloc another timer, that's a big leak since you're never releasing those references.
tmLeftTime = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateLeftTime:) userInfo:nil repeats:YES];
And in your updateTimeLeft: just re-schedule the timer's method and set a condition where it should stop.
tmLeftTime = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateLeftTime:) userInfo:nil repeats:YES];

Related

NSTimer not stopping?

I'm trying to to stop an NSTimer with the following code:
- (void)viewDidLoad
{
[super viewDidLoad];
timer3 = [NSTimer timerWithTimeInterval:5.0 target:self selector:#selector(start) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer3 forMode:NSDefaultRunLoopMode];
}
-(void)invalidate
{
[timer3 invalidate];
timer3 = nil;
}
and I call -(void)invalidate from another class like this:
-(void)timer
{
ClassOfMyTimer *class = [[ClassOfMyTimer alloc] init];
[class invalidate];
}
but the timer doesn't stop. Does anyone know what I'm doing wrong?
You need to call your invalidate method on the same instance of your class that created the timer. In your timer method you create a new instance of your class which could have its own timer and invalidate that.
I'm kind of confused by what you're trying to do here, but I'd guess that you're not maintaining a reference to timer3.
Have you created a property in the .h file for the timer:
#property (strong) NSTimer *timer3;
And then added a synthesize statement in the .m file:
#synthesize timer3;
Then, in viewDidLoad:, you can maintain a reference to the timer you're creating via:
self.timer3 = [[[NSTimer timerWithTimeInterval:5.0 target:self selector:#selector(start) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer3 forMode:NSDefaultRunLoopMode];
And, to invalidate the timer later:
[self.timer3 invalidate]
self.timer3 = nil
On preview, Sven also has a valid solution to an issue that might be impacting you..

NSTimer causes crash

The following method causes a crash. The UI is like a button, which handles the start / stop functionality of the NSTimer. If the timer runs, a UILabel is updated. Using the viewDidLoad Method makes my timer work, stopping it works too, but starting it again crashes the app.
Removing the alloc in the viewDidLoad method and trying to use the start button causes a crash instantly. Even the NSLog(#"Start now");is not called.
Code:
- (void)tick {
NSLog(#"tick");
float value = [moneyLabel.text floatValue];
moneyLabel.text = [NSString stringWithFormat:#"%f", value + 1.0];
}
- (IBAction)startStopButtonClicked:(UIButton *)sender {
if ([sender.titleLabel.text isEqualToString:#"Start"]) {
NSLog(#"Start now");
if (timer) {
NSLog(#"Timer valid");
[timer fire];
} else {
NSLog(#"Timer is nil");
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(tick) userInfo:nil repeats:YES];
[timer fire];
}
NSLog(#"bla");
[sender setTitle:#"Stop" forState:UIControlStateNormal];
} else {
[timer invalidate];
timer = nil;
NSLog(#"Stopped.");
NSLog(#"Timer isValid: %#", timer);
[sender setTitle:#"Start" forState:UIControlStateNormal];
}
}
I don't see the need to call [NSTimer fire] at all; it should be enough to allow the timer to decide when to fire.
Firstly ensure that timer is nil (it should be if it's an instance variable of the object), although explicitly setting it to nil in - (id)init won't hurt.
Next I would use the state of the timer itself to determine whether start/stop has been pressed, not the text in the button:
- (IBAction)startStopButtonClicked:(UIButton *)sender
{
if (timer != nil)
{
NSLog(#"Stopping timer");
[timer invalidate];
timer = nil;
}
else
{
NSLog(#"Starting timer");
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(tick)
userInfo:nil
repeats:YES];
}
[sender setTitle:(timer != nil ? #"Stop" : #"Start")
forState:UIControlStateNormal];
}
The code you have posted works as desired - just tested it in a new project, so the problem could be somewhere else. I tested it only by declaring the ivar NSTimer *timer; without any initialization in viewDidLoad: or the designated initializers...

NSTimer Uniqe question

I'll go straight to the problem.
This ones eating my head since a week.
What i intend to do is set my timer, which is supposed to be fired on main run loop, from a secondary thread. So i do it as follows.
if(timerRefresh)
{
//[timerRefresh invalidate];
timerRefresh = nil;
}
if (!self.isConnectionAvailable) {
timerRefresh = [NSTimer timerWithTimeInterval:appDelegate.TimerInterval target:self selector:#selector(startAutoRefresh) userInfo:nil repeats:NO];
}
else if (self.isLivePresent||self.isUpcomingMatchToday) {
timerRefresh = [NSTimer timerWithTimeInterval:appDelegate.TimerInterval target:self selector:#selector(startAutoRefresh) userInfo:nil repeats:NO];
}
else {
timerRefresh = [NSTimer timerWithTimeInterval:LongRefresh target:self selector:#selector(startAutoRefresh) userInfo:nil repeats:NO];
}
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
[runLoop addTimer:timerRefresh forMode:NSDefaultRunLoopMode];
[runLoop run];
When this fires, a loader begins loading on the main thread, and the processing work is done on the secondary thread.
I hope this is a correct way.
Now i have a child class within this main class which also has to show a loader while it triggers a filtering process, so to avoid multiple loaders, when the the filtering process triggers, i pause the refreshing on this parent class, by sending it notifications from the child class..like this...
-(void)teamNameClicked:(id)sender
{
BOOL result = YES;
NSNumber *newNumber = [NSNumber numberWithBool:result];
[[NSNotificationCenter defaultCenter] postNotificationName:#"PauseMatchesLiveMatchTimer" object:newNumber];
[self performSelector:#selector(sendTeamNameClickToFunction:) withObject:sender];
}
and when operation completes i have another notifier as this...
-(void)processTeamNameClick:(id)sender
{
UIButton *button = (UIButton *)sender;
selectedIndexDropDown = button.tag;
[self parseTeamFile:button.tag];
self.lblDropDown.text = [dictTeamFilter valueForKey:[NSString stringWithFormat:#"%i",button.tag]];
[tblResults performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
BOOL result = NO;
NSNumber *newNumber = [NSNumber numberWithBool:result];
[[NSNotificationCenter defaultCenter] postNotificationName:#"PauseMatchesLiveMatchTimer" object:newNumber];
}
Notice the YES and NO for results..
Now this is an observer for the notification...
-(void)pauseAndResumeTimer:(NSNotification *)notification;
{
NSNumber *newNumber = [notification object];
BOOL result = [newNumber boolValue];
if (result) {
if(timerRefresh)
{
if ([timerRefresh isValid])
[timerRefresh invalidate];
timerRefresh = nil;
}
}
else
{
if(timerRefresh)
{
if ([timerRefresh isValid])
[timerRefresh invalidate];
timerRefresh = nil;
}
if (!self.isConnectionAvailable) {
timerRefresh = [NSTimer timerWithTimeInterval:appDelegate.TimerInterval target:self selector:#selector(startAutoRefresh) userInfo:nil repeats:NO];
}
else if (self.isLivePresent||self.isUpcomingMatchToday) {
timerRefresh = [NSTimer timerWithTimeInterval:appDelegate.TimerInterval target:self selector:#selector(startAutoRefresh) userInfo:nil repeats:NO];
}
else {
timerRefresh = [NSTimer timerWithTimeInterval:LongRefresh target:self selector:#selector(startAutoRefresh) userInfo:nil repeats:NO];
}
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
[runLoop addTimer:timerRefresh forMode:NSDefaultRunLoopMode];
[runLoop run];
}
}
When the filtering process is on, i stop the parent timer. And when off i start it again.
Ok...So now the problem... When i do normal navigation on my pages, it works absolutely fine..like switching tabs, traversing between pages etc.
But if i use the filter process, somehow, it triggers my timer on the main page, and even when the view has disappeared, seems to kick off my timer event. I want to avoid that, but i just dont know how..
If anyone can genuinely help me, please do.
Thanks in advance.
There is some funny stuff going on in your code:
First and formemost, I am at least least 90% positively sure that you don't want to call [[NSRunLoop mainRunLoop] run] in any of your program's methods — do those methods even exit, or do you keep aggregating thread upon thread?
Secondly, your timer invalidations are all a bit strange:
There is no use in if (timerRefresh) if ([timerRefresh isValid]) [timerRefresh invalidate];; since in Objective C, messaging nil is perfectly fine. The result of such a message is always 0x0, so the first if is unnecessary and the second one evaluates to NO in that case, anyway.
Invalidating a timer means removing it from the runloop it was scheduled on. Hence, the second if is unnecessary, too — leaving you with just [timerRefresh invalidate];.
For -[NSTimer invalidate] to have an effect, it needs to be called on the thread the timer is scheduled on. From what I understood, this is not the case in all your methods. So you should use performSelectorOnMainThread:withObject:waitUntilDone: with the appropriate arguments instead.
There is no difference between [self performSelector:#selector(sendTeamNameClickToFunction:) withObject:sender] and simply [self sendTeamNameClickToFunction:sender]. Except that the latter is much easier to read ;-)
The if clauses in pauseAndResumeTimer: don't make an awful lot of sense, i.e. there's a lot of code duplication.
Here is said method in a tidied-up fashion and with the invalidation happening on the main thread:
-(void)pauseAndResumeTimer:(NSNotification *)notification
{
[timerRefresh performSelectorOnMainThread:#selector(invalidate) withObject:nil waitUntilDone:YES];
timerRefresh = nil;
NSNumber *result = [notification object];
if ([result boolValue]) return;
if ( !self.isConnectionAvailable || self.isLivePresent || self.isUpcomingMatchToday ) {
timerRefresh = [NSTimer timerWithTimeInterval:appDelegate.TimerInterval target:self selector:#selector(startAutoRefresh) userInfo:nil repeats:NO];
} else {
timerRefresh = [NSTimer timerWithTimeInterval:LongRefresh target:self selector:#selector(startAutoRefresh) userInfo:nil repeats:NO];
}
[[NSRunLoop mainRunLoop] addTimer:timerRefresh forMode:NSDefaultRunLoopMode];
}

How can I make a counter?

How can I make a counter from 0 to 10 choosing the delay?
you need to use NSTimer,
Check the below code as reference.
- (void) startCounter {
counterCount = 0;
[NSTimer scheduledTimerWithInterval:0.09f target:self selector:#selector(showElapsedTime:) userInfo:nil repeats:YES];
}
showElapsedTime will be called after delay, you provide.
-(void) showElapsedTime: (NSTimer *) timer {
counterCount++;
if(counterCount == 10)
{
[timer invalidate];
}
// Write your code here
}
Create an NSTimer:
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
target:(id)target
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)repeats;
Yours would probably look like this:
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(timerFired:)
userInfo:nil
repeats:YES];
In the method that is invoked, increment a counter, and check to see if you've hit your count to stop the timer:
- (void)timerFired:(NSTimer *)timer
{
static int counter = 0;
// Do Something
counter++;
if(counter == 10)
[timer invalidate];
}
The method [performSelector: withObject: afterDelay] of the NSObject class is normally used for timed operations.

Retaining object created by a class method?

This is probably something I should know by now, I am creating an instance of NSTimer using the NSTimer class method. I am pretty sure the returned object is autoreleased, my question is in terms of memory management should I be then retaining and releasing the timer object (METHOD: 1), or simply just assigning it directly to the #property (METHOD: 2)(or should I be doing something totally different?)
// METHOD: 1
#property (nonatomic, retain) NSTimer *myTimer;
.
NSTimer *tempTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(executeOnTimer) userInfo:nil repeats:YES];
[self setMyTimer:tempTimer];
//[tempTimer release];
.
- (void)dealloc {
[pulseTimer release];
[super dealloc];
}
OR SIMPLY:
// METHOD: 2
myTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(executeOnTimer) userInfo:nil repeats:YES];
EDIT:
One final point, if I just write (see below) without assigning to a property is there any chance that the timer is going to get deallocated, basically does it stay around until the program exits. Just curious how its retained?
[NSTimer scheduledTimerWithTimeInterval:120.0 target:self selector:#selector(executeOnTimer) userInfo:nil repeats:YES];
In order to take ownership over the NSTimer you can do one of these with the same effect:
self.myTimer = [NSTimer scheduledTimerWithTimeInterval: ...]; // implicit setter
or
[self setMyTimer: [NSTimer scheduledTimerWithTimeInterval:...]]; // explicit setter
or
myTimer = [[NSTimer scheduledTimerWithTimeInterval: ...] retain];
or
self->myTimer = [[NSTimer scheduledTimerWithTimeInterval: ...] retain];
This is the good way:
self.myTimer = tempTimer;
// don't call [tempTimer release]
This will retain it automcailcally due to the property which retains it.
Just calling myTimer = … doesn't use the setter while self.myTimer = … does.