gpt4 book ai didi

swift - block 没有真正执行?

转载 作者:行者123 更新时间:2023-11-30 13:56:11 24 4
gpt4 key购买 nike

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

下面是我的代码和输出。该 block 正在创建并添加到数组中,并且应该由线程出列并运行,但我没有看到 block 运行产生的任何输出。为什么不呢?

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 。您需要 block(),例如:

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com