块不是真的执行吗

块不是真的执行吗

我正在尝试使用NSThread的子类来运行一些命令。在您推荐NSOperation或GCD之前,是的,我需要使用线程。

以下是我的代码和输出。正在创建该块并将其添加到数组,并且据说该块已由线程出队并运行,但是我看不到块的运行会产生任何输出。为什么不?

import UIKit

class ViewController: UIViewController {

    private let _queue = dispatch_queue_create("com.AaronLBratcher.ALBQueue", nil)
    private let _thread = TestThread()
    private let _lock = NSCondition()

    override func viewDidLoad() {
        super.viewDidLoad()

        _thread.start()

        var openSuccessful = false

        dispatch_sync(_queue) {[unowned self] () -> Void in
            self._lock.lock()
            self._thread.openFile("file path here", completion: { (successful) -> Void in
                print("completion block running...")
                openSuccessful = successful
                self._lock.signal()
                self._lock.unlock()
            })
            self._lock.wait()
        }

        print("open operation complete")
        print(openSuccessful)
    }


    final class TestThread:NSThread {
        var _iterations = 0
        var _lock = NSCondition()
        var _blocks = [Any]()

        func openFile(FilePath:String, completion:(successful:Bool) -> Void) {
            print("queueing openFile...")

            let block = {[unowned self] in
                self._iterations = self._iterations + 1
                print("opening file...")
                completion(successful: true)
            }

            addBlock(block)
        }

        func addBlock(block:Any) {
            _lock.lock()
            _blocks.append(block)
            _lock.signal()
            _lock.unlock()
        }

        override func main() {
            _lock.lock()
            while true {
                while _blocks.count == 0 {
                    print("waiting...")
                    _lock.wait()
                }

                print("extracting block...")
                if let block = _blocks.first {
                    _blocks.removeFirst()
                    _lock.unlock()
                    print("running block...")
                    block;
                }

                _lock.lock()
            }
        }
    }
}


输出:

queueing openFile...
waiting...
extracting block...
running block...
waiting...

最佳答案

该块未运行,因为您只有block。您需要block(),例如:

if let block = _blocks.first as? ()->() {
    _blocks.removeFirst()
    _lock.unlock()
    print("running block...")
    block()
}

关于swift - 块不是真的执行吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33586410/

10-10 02:57