Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to be able to execute a delay every time that a function loops through a loop. I already have a loop setup, as shown below:

for (float batteryPercentage = 1; batteryPercentage <= 0; batteryPercentage -= 0.01)
    {
        double timeUntilNextDegreeDrop = 9.0;
        dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeUntilNextDegreeDrop * NSEC_PER_SEC));
        dispatch_after (time, dispatch_get_main_queue(), ^(void)
        {
            [batteryLevel setProgress:batteryPercentage animated:YES];

            float batteryLevelPercentage = batteryPercentage * 100;
            batteryLevelLabel.text = [NSString stringWithFormat:@"Battery Level: %f%%", batteryLevelPercentage];
        });
    }

batteryPercentage is the variable that I am trying to decrement from 1 to 0 by 0.01 every 9 seconds until the value reaches 0. The total length of the program should be 900 seconds (15 minutes). Every 9 seconds, I want this code to execute every nine seconds and to change the value of the UIProgressView called batteryLevel. Then, I want to multiply batteryPercentage by 100, to get a whole percentage number, such as multiplying 0.67 to get 67, then replace the batteryLevelLabel text with the new value. When I try and execute this, the batteryLevel Progress View simply doesn't fill and the text doesn't change. I'm assuming there's something wrong with the timer, so what would be a more effective way of inputing a 9 second delay?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
125 views
Welcome To Ask or Share your Answers For Others

1 Answer

try with nstimer as suggested

[NSTimer scheduledTimerWithTimeInterval:9.0
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];

//targetMethod will be called every 9 second //call [myTimer invalidate]; myTimer = nil; when your task is done


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...