取消 NSOperationQueue

Cancel NSOperationsQueue

我正在尝试取消我的 NSOperationsQueue 并从队列中删除所有操作。我调用了方法 "cancelAllOperations()" 但这并没有从队列中删除操作,我知道这个方法只是向操作添加了一个标志。

如何从我的队列中删除所有操作?或者阻止操作队列执行带有标志的操作?

private let mediaDownloadOperationQueue: NSOperationQueue = {
    let queue = NSOperationQueue()
    queue.maxConcurrentOperationCount = 1
    queue.qualityOfService = .Background

    return queue
}()

func startDownloadProcess() {
    guard downloadSwitchState == true else { return }

    let context = DataBaseManager.sharedInstance.mainManagedObjectContext
    let mediasToDownload = self.listOfMediaToDownload(context)

    for media in mediasToDownload {
        downloadMedia(media)
    }
}

private func downloadMedia(media: Media) {
    //check if operation already exist
    for operation in mediaDownloadOperationQueue.operations {
        let operation = operation as! MediaDownloadOperation

        if operation.media.objectID == media.objectID { return }
    }

    //HERE I am adding the operation to queue
    mediaDownloadOperationQueue.addOperation(MediaDownloadOperation(media: media))
}

//编辑:这是我的 MediasDownloadOperation

import Foundation
import Alamofire

class MediaDownloadOperation: BaseAsyncOperation {

    let media: Media
    init(media: Media) {
        self.media = media
        super.init()
    }

    override func main() {
        guard let mediaSourceURI = media.sourceURI
        else {
            self.completeOperation()
            return
        }   

        var filePath: NSURL?
        let destination: (NSURL, NSHTTPURLResponse) -> (NSURL) = {
            (temporaryURL, response) in

            if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first, let suggestedFilename = response.suggestedFilename {
                filePath = directoryURL.URLByAppendingPathComponent("\(suggestedFilename)")
                return filePath!
            }
        return temporaryURL
    }

        RequestManager.sharedAlamofireManager.download(.GET, mediaSourceURI, destination: destination).response {
            (request, response, data, error) -> Void in

            if let filePath = filePath where error == nil {
                let saveToCameraRoll = self.media.saveToCameraRoll?.boolValue == true

                self.media.fileLocation = filePath.lastPathComponent
                self.media.saveToCameraRoll = false

                DataBaseManager.sharedInstance.save()

                if saveToCameraRoll {
                    self.media.saveMediaToCameraRoll(nil)
                }
            }

            self.completeOperation()
            NSNotificationCenter.defaultCenter().postNotificationName(MediaDownloadManager.MediaIsDownloadedNote, object: nil)

        }
    }
}

添加条件测试以查看操作是否已取消似乎已经解决了问题:

    RequestManager.sharedAlamofireManager.download(.GET, mediaSourceURI, destination: destination).response {
        (request, response, data, error) -> Void in

        //Only download if logged in
        if (self.cancelled == false){
            print("RAN operation!")
            if let filePath = filePath where error == nil {
                let saveToCameraRoll = self.media.saveToCameraRoll?.boolValue == true

                self.media.fileLocation = filePath.lastPathComponent
                self.media.saveToCameraRoll = false

                DataBaseManager.sharedInstance.save()

                if saveToCameraRoll {
                    self.media.saveMediaToCameraRoll(nil)
                }
            }

            self.completeOperation()

            NSNotificationCenter.defaultCenter().postNotificationName(MediaDownloadManager.MediaIsDownloadedNote, object: nil)
        }else{
            print("did not run operation!  was cancelled!")
            self.completeOperation()
        }
    }