简体   繁体   中英

iOS Swift - How to reference a NSOperationQueue in an extension to cancel existing operations?

I am creating an extension for NSURL that basically validates that a URL exists and returns a valid site.

I am using NSURLConnection.sendAsynchronousRequest(...) for this process to actually check the http header response, and it works great.

However, in my case I am detecting the provided URL in a textfield after every update to the text , and want to try to improve performance by canceling any existing NSURLConnection requests. I think the only way to do this, is to create a 'referencable' NSOperationQueue that I can then call 'myOperationQueue.cancelAllOpertions()' on.

So my question is, how can I create a referencable NSOperationQueue that I can call the appropriate 'cancelAllOperations()' on each time this validation function is called so it will stop any running operations?

Again, since this is a Class Extension, I can't just create a global variable for the operation queue, and reference it using 'self.myOperationQueue'.

You can add a nested type to NSURL with a static variable to hold the queue. That way you'll always have access to the same queue from within your extension methods:

extension NSURL {
    struct RequestQueue {
        static var queue = NSOperationQueue()
    }

    func checkURL() {
        println(RequestQueue.queue)
    }
}

let myURL = NSURL(string: "http://natecook.com/")!
myURL.checkURL()
// <NSOperationQueue: 0x7fe81b7022e0>{name = 'NSOperationQueue 0x7fe81b7022e0'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM