如何在Swift中将值传递给完成处理程序?

时间:2017-03-14 02:11:10

标签: swift asynchronous asynccallback

我想将整数传递给完成处理程序。因为处理程序是异步的,所以当完成处理程序有机会运行时,count的值可能是不准确的?我想将count的CURRENT值传递给处理程序,以便在调用处理程序时计数是准确的。我该怎么做?

// 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...

            })
        }
    }

1 个答案:

答案 0 :(得分:0)

由于此函数中没有count的声明,我将假设count是一个参数。如果是这样,那么使用count访问self.count(块中必填)将获得count的最新值,即使它在您致电captureStillImageAsynchronously()后发生变化。

如果有多个来源可以同时写入和读取count,则应确保它是线程安全的。

相关问题