PDA

View Full Version : [Resolved] Timer update help




nickculbertson
Jun 1, 2011, 12:46 PM
Hello,
I have a sound that plays when a button is touched. 17 seconds later I want another action to be called using performSelector to stop the sound. If the first button is touched again before the 17 seconds have been reached I want the counter to restart. How can this be done?

-(IBAction) push{
[sound play];
[self performSelector:@selector (stop) withObject:nil afterDelay:17.];
}

-(void) stop{
[sound stop];
}

Thanks,
Nick



chown33
Jun 1, 2011, 01:19 PM
As always, start by reading the class reference doc:
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html

From the class reference doc, you should be able to figure out how to do the following. What follows is a simple breakdown of your description into logical steps. You should be able to do simple breakdowns like this yourself; it's an important skill called decomposition.
http://en.wikipedia.org/wiki/Decomposition_(computer_science)


Make and schedule an NSTimer using
+scheduledTimerWithTimeInterval:target:selector:userInfo:repeats

Take ownership of the timer, and store in an ivar (or assign to a retain'ed property) for later use.

When the button is pressed, look at the stored timer. If it's valid (what method for this?), then the 17 sec interval has not expired. Do action A. If the stored timer is nil or invalid, then the interval has expired. Do action B. The actions A and B are whatever are relevant to playing or stopping the sound, etc.

When the timer fires, the interval has expired, so do action B. That is, action B should be used as the target/action when the timer was first made.

When the timer's use is completed (after action A or B), remove it from storage. Consider whether this can be done as part of actions A and B.

nickculbertson
Jun 1, 2011, 02:27 PM
Thanks for the tip, chown33.

This did the trick


-(IBAction) push{
[sound play];
[time1 invalidate];
time1 = [NSTimer scheduledTimerWithTimeInterval:17.0 target:self selector:@selector(stop) userInfo:nil repeats:NO];
}

-(void) stop{
[sound stop];
time1=nil;
}

Thanks,
Nick