Objective-c Method to get a number then countdown in 1 every second
i need a little help i have a method which gets value such as 50, it then assigns that value to trackDuration, so NSNumber *trackDuration = 50, i want the method to every second minus 1 from the value of trackDuration and update a label, the label being called duration.
Here's what i have so far;
- (void) countDown {
iTunesApplication *iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
NSNumber *trackDuration = [NSNumber numberWithDouble:[[iTunes currentTra开发者_开发知识库ck] duration]];
while (trackDuration > 0) {
trackDuration - 1;
int inputSeconds = [trackDuration intValue];
int hours = inputSeconds / 3600;
int minutes = ( inputSeconds - hours * 3600 ) / 60;
int seconds = inputSeconds - hours * 3600 - minutes * 60;
NSString *trackDurationString = [NSString stringWithFormat:@"%.2d:%.2d:%.2d", hours, minutes, seconds];
[duration setStringValue:trackDurationString];
sleep(1);
}}
Any help would be much appreciated, thanks in advanced, Sami.
This will block the main thread, and you are not assigning the value trackDuration, so it will always stay 50
trackDuration -1;
Should be:
trackDuration--; // or trackDuration -= 1;
Also I would do it like this:
- (void)startCountDown
{
[NSTimer scheduledTimerWithInterval:1.0f target:self selector:@selector(timerHit:) userInfo:nil repeats:YES];
}
- (void)timerHit:(NSTimer *)p_timer
{
if( trackDuration <= 1 && [p_timer isValid] )
[p_timer invalidate];
// track duration is an instance variable
trackDuration--;
// update LABEL
}
iOS 2.x or higher is required for NSTimer
Having this method run in a loop will make your app go unresponsive for the whole time it's running — you won't even see any UI updates. Instead, you should use an NSTimer with an interval of one second, and update the elapsed time when the timer fires.
精彩评论