本文介绍了Objective-C时间延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当一个函数循环一个循环时,我希望能够执行一个延迟。我已经有一个循环设置,如下所示:

  for(float batteryPercentage = 1; batteryPercentage  {
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 是变量,我试图从1到0每9秒递减0.01,直到值达到0.程序的总长度应该是900秒(15分钟)。每9秒钟,我希望此代码每9秒执行一次,并更改名为 batteryLevel UIProgressView 的值。然后,我想将 batteryPercentage 乘以100,得到一个整数百分数,例如乘以0.67得到67,然后替换 batteryLevelLabel 文本与新值。当我尝试执行此操作时, batteryLevel Progress View不会填充,文本也不会更改。我假设定时器有什么问题,那么输入一个9秒延迟的更有效的方法是什么?解决方案

>按照建议尝试使用nstimer

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



// targetMethod每9秒调用
//调用
[myTimer invalidate]; myTimer = nil; 任务完成时


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?

解决方案

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

这篇关于Objective-C时间延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:41