2015-10-14 70 views
1

在我的用户界面中,当点击一个按钮时,它会调用一个顺序执行多个任务的for循环。在不阻挡用户界面的情况下在循环中添加延迟

// For Loop 
for (int i = 1; i <= 3; i++) 
{ 
    // Perform Task[i] 
} 
// Results: 
// Task 1 
// Task 2 
// Task 3 

每个任务后,我想添加一个用户定义的延迟。例如:

// For Loop 
for (int i = 1; i <= 3; i++) 
{ 
    // Perform Task[i] 
    // Add Delay Here 
} 

// Results: 
// 
// Task 1 
// Delay 2.5 seconds 
// 
// Task 2 
// Delay 3 seconds 
// 
// Task 3 
// Delay 2 seconds 

在iOS系统中,使用Objective-C,是有没有办法中的添加这种延误for循环,记住:

  1. 的UI应该保持响应。
  2. 这些任务必须按顺序执行。

for循环的上下文中的代码示例将是最有帮助的。谢谢。

回答

0

此解决方案是否可行?我没有使用dispatch_after,而是使用带有[NSThread sleepForTimeInterval]块的dispatch_async,它允许我在自定义队列中放置任何需要的延迟。

dispatch_queue_t myCustomQueue; 
myCustomQueue = dispatch_queue_create("com.example.MyQueue", NULL); 

dispatch_async(myCustomQueue,^{ 
    NSLog(@“Task1”); 
}); 

dispatch_async(myCustomQueue,^{ 
    [NSThread sleepForTimeInterval:2.5]; 
}); 

dispatch_async(myCustomQueue,^{ 
    NSLog(@“Task2”); 
}); 

dispatch_async(myCustomQueue,^{ 
    [NSThread sleepForTimeInterval:3.0]; 
}); 

dispatch_async(myCustomQueue,^{ 
    NSLog(@“Task3”); 
}); 

dispatch_async(myCustomQueue,^{ 
    [NSThread sleepForTimeInterval:2.0]; 
}); 
5

使用GCDdispatch_after。 你可以在stackoverflow上搜索它的用法。 尼斯制品是1.5秒延时在夫特here

简要例如:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 1.5)), dispatch_get_main_queue()) { 
    // your code here after 1.5 delay - pay attention it will be executed on the main thread 
} 

和目标c:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{ 
    // your code here after 1.5 delay - pay attention it will be executed on the main thread 
}); 
+0

但是,你将如何处理在循环的最后一次迭代的延迟?我需要在退出循环之前延迟。我无法调用dispatch_after,因为在循环中的最后一个任务之后没有实际的代码块要执行。 – Oak

1

这听起来像NSOperationQueue与延迟的理想的工作正在实施像这样:

@interface DelayOperation : NSOperation 
@property (NSTimeInterval) delay; 
- (void)main 
{ 
    [NSThread sleepForTimeInterval:delay]; 
} 
@end 
+0

你能提供一个更完整的例子来复制上面的示例代码中的for循环吗? – Oak

+0

@Oak您将通过阅读“NSOperationQueue”文档获取该文档;无论如何,你会想要阅读它们。 – l00phole

0

继承人斯威夫特版本:

func delay(seconds seconds: Double, after:()->()) { 
    delay(seconds: seconds, queue: dispatch_get_main_queue(), after: after) 
} 

func delay(seconds seconds: Double, queue: dispatch_queue_t, after:()->()) { 
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))) 
    dispatch_after(time, queue, after) 
} 

你怎么称呼它:

print("Something")  
delay(seconds: 2, after: {() ->() in 
    print("Delayed print")  
}) 
print("Anotherthing")  
相关问题