2015-10-14 49 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")  
相關問題