2016-08-18 2 views
0

진행중인 모든 작업의 ​​실행이 완료되면 NSOperationQueue 할당을 해제하려고합니다. 지금까지 아래 코드를 작성했으나 waitUntilAllOperationsAreFinished은 비동기 호출이며 nil을 얻는 operationQueue에서 보유 할 수 없습니다.대기열의 모든 작업이 끝나자 마자 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?() 
       }) 
      } 
     } 
    } 

} 

완료되면 : 제로에 도달 할 때까지

- (void)deallocOperationQueue 
{ 
    [operationQueue waitUntilAllOperationsAreFinished]; 
    operationQueue = nil; 
} 
+0

이름에'wait'가있는 메소드가 비동기라고 생각하는 이유는 무엇입니까? – Avi

+0

당신은 그 문제를 잘못된 길로 생각하고 있습니다. 큐에 대한 강력한 참조가 없을 때 큐가 dealloc됩니다. 참조를 더 이상 필요로하지 않을 때는'nil'을 참조로 설정해야합니다. 더 이상 대기열이 필요하지 않을 때는 참조를 설정하지 마십시오. – Avi

+0

나는 프로젝트 전체에 살아있는 컨트롤러 클래스를 사용하고있다. dealloc 등에서 nil로 설정할 수 없습니다. –

답변

1

Avi

를 인용

모든 작업이 끝날 때까지 기다릴 필요가 없습니다. 작업이 끝나면 operationQueue를 0으로 설정하면됩니다. 큐에 여전히 작업이 있으면 아무 작업도 수행되지 않습니다. 그들은 여전히 ​​완성 될 것입니다.

- (void)deallocOperationQueue 
{ 
    operationQueue = nil; 
} 

나는 코드를 테스트 일어날 않는 언급 동작을 확인했다.

0

당신은 NSOperationQueue를 서브 클래스와 작업을 키 경로를 관찰 할 수

var operationQueue: DownloadOperationQueue? = DownloadOperationQueue() 

// Add your operations ... 

operationQueue?.completionBlock = { 
    operationQueue = nil 
}