我想在正在执行的所有操作完成后释放NSOperationQueue。
到目前为止,我已在下面进行了编码,但据我所知,waitUntilAllOperationsAreFinished
是异步调用,无法保持我的operationQueue为零。
- (void)deallocOperationQueue
{
[operationQueue waitUntilAllOperationsAreFinished];
operationQueue = nil;
}
答案 0 :(得分:1)
引用Avi
您不需要等待所有操作完成。刚设置 当你完成它时,operationQueue为nil。如果队列仍然有 操作,没有任何反应;他们仍然会完成。
- (void)deallocOperationQueue
{
operationQueue = nil;
}
我已经测试了代码并确认所声明的行为确实发生了。
答案 1 :(得分:0)
您可以对NSOperationQueue进行子类化并观察操作键路径,直到它达到零:
class DownloadOperationQueue: NSOperationQueue {
private static var operationsKeyPath: String {
return "operations"
}
deinit {
self.removeObserver(self, forKeyPath: "operations")
}
var completionBlock: (() -> Void)? {
didSet {
self.addObserver(self, forKeyPath: DownloadOperationQueue.operationsKeyPath, options: .New, context: nil)
}
}
override init() {
super.init()
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let operationPath = keyPath where operationPath == DownloadOperationQueue.operationsKeyPath {
if self.operations.count == 0 {
NSOperationQueue.mainQueue().addOperationWithBlock({
self.completionBlock?()
})
}
}
}
}
完成后:
var operationQueue: DownloadOperationQueue? = DownloadOperationQueue()
// Add your operations ...
operationQueue?.completionBlock = {
operationQueue = nil
}