简体   繁体   English

iOS Swift - 如何在扩展中引用 NSOperationQueue 以取消现有操作?

[英]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.我正在为 NSURL 创建一个扩展,它基本上验证一个 URL 存在并返回一个有效的站点。

I am using NSURLConnection.sendAsynchronousRequest(...) for this process to actually check the http header response, and it works great.我在这个过程中使用 NSURLConnection.sendAsynchronousRequest(...) 来实际检查 http 标头响应,并且效果很好。

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.但是,在我的情况下,我在每次更新文本后检测文本字段中提供的 URL,并希望通过取消任何现有的 NSURLConnection 请求来尝试提高性能。 I think the only way to do this, is to create a 'referencable' NSOperationQueue that I can then call 'myOperationQueue.cancelAllOpertions()' on.我认为唯一的方法是创建一个“可引用”的 NSOperationQueue,然后我可以调用它“myOperationQueue.cancelAllOpertions()”。

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?所以我的问题是,我如何创建一个可引用的 NSOperationQueue,我可以在每次调用此验证函数时调用适当的“cancelAllOperations()”,以便停止任何正在运行的操作?

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'.同样,由于这是一个类扩展,我不能只为操作队列创建一个全局变量,并使用“self.myOperationQueue”来引用它。

You can add a nested type to NSURL with a static variable to hold the queue.您可以使用静态变量向NSURL添加嵌套类型以保存队列。 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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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