如何在Swift中将值传递给完成处理程序?
我想将一个整数传递给一个完成处理程序。因为处理程序是异步的,所以当完成处理程序有机会运行时,count的值可能不准确?我想将count的当前值传递给处理程序,以便在调用处理程序时count是准确的。我该怎么做如何在Swift中将值传递给完成处理程序?,swift,asynchronous,asynccallback,Swift,Asynchronous,Asynccallback,我想将一个整数传递给一个完成处理程序。因为处理程序是异步的,所以当完成处理程序有机会运行时,count的值可能不准确?我想将count的当前值传递给处理程序,以便在调用处理程序时count是准确的。我该怎么做 // Take image func didPressTakePhoto(){ if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo){
// Take image
func didPressTakePhoto(){
if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo){
videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait
count = count + 1
//Capture image. everything in this closure is ASYNCHRONOUS?
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {
(sampleBuffer, error) in
//Do something with count...
})
}
}
由于此函数中没有对
count
的声明,因此我假定count
是一个参数。如果是这样,那么使用self.count
(在一个块中必须)访问count
,将获得count
的最新值,即使它在异步调用captureStillImageAsynchronously()
后发生变化
如果多个源有可能同时写入和读取
count
,则应确保它是线程安全的。我将count outside声明为全局变量。