我对obj c比较新,所以对于我的学校工作,我需要在(相同)函数中执行三行之间添加延迟。是否有任何有利的选择?
line 1: [executing first operation];
line 2: Delay /* I need to introduce delay here */
line 3: [executing second operation];
line 4: Delay /* I need to introduce delay here again */
line 5: [executing second operation];
在此先感谢,任何帮助将不胜感激。
答案 0 :(得分:0)
所以我找到的解决方案是:
[operation 1]
double delayInSeconds = 9.3;
dispatch_time_t popTime2 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[operation 2];
double delayInSeconds2 = 9.3;
dispatch_time_t popTime2 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds2 * NSEC_PER_SEC));
dispatch_after(popTime2, dispatch_get_main_queue(), ^(void){
[operation 3];
});
});
这是正确的方法吗? 如果是的话,无论如何我都不需要在操作2的延迟中嵌套操作3
答案 1 :(得分:0)
你可以通过NSRunLoop方法实现目标 - (void)performSelector:(SEL)aSelector withObject :( nullable id)anArgument afterDelay:(NSTimeInterval)delay;
[executing first operation];
[self performSelector:@selector(2nd_Operation) withObject:nil
afterDelay:1st_Delay_In_Seconds];
[self performSelector:@selector(3rd_Operation) withObject:nil
afterDelay:2nd_Delay_In_Seconds];
请注意,如果您将上述代码放在一个方法中,则两个延迟时间几乎同时开始。如果你想在0.5s延迟后调用2nd_operation然后在另外0.5s延迟后调用3rd_operation,那么2nd_Delay_Time应该是0.5s + 2nd_operation执行时间+0.5s。如果由于某种原因需要准确的延迟,我建议将最后一行放在2nd_operation的完整块中。