取消封装在 NSOperation 中的 Alamofire 请求会导致多个 KVO?

2024-04-08

我的Xcode版本:6.3.2
Alamofire 版本:1.2.2(通过 Cocoapods 安装)

为了设置maxConcurrentOperationCount限制并发操作数NSOperationQueue,我包裹我的阿拉莫菲尔 https://github.com/Alamofire/AlamofireNSOperation 中的下载请求就像罗布建议的那样 https://stackoverflow.com/a/27022598/1576281.

的基本子类NSOperation像这样:

class ConcurrentOperation : NSOperation {

    override var concurrent: Bool {
        return true
    }

    override var asynchronous: Bool {
        return true
    }

    private var _executing: Bool = false
    override var executing: Bool {
        get {
            return _executing
        }
        set {
            if (_executing != newValue) {
                self.willChangeValueForKey("isExecuting")
                _executing = newValue
                self.didChangeValueForKey("isExecuting")
            }
        }
    }

    private var _finished: Bool = false;
    override var finished: Bool {
        get {
            return _finished
        }
        set {
            if (_finished != newValue) {
                self.willChangeValueForKey("isFinished")
                _finished = newValue
                self.didChangeValueForKey("isFinished")
            }
        }
    }

    /// Complete the operation
    ///
    /// This will result in the appropriate KVN of isFinished and isExecuting

    func completeOperation() {
        executing = false
        finished  = true
    }

    override func start() {
        if (cancelled) {
            finished = true
            return
        }

        executing = true

        main()
    }
}

我的子类包装了一个 Alamofire 下载请求,如下所示:

class DownloadImageOperation : ConcurrentOperation {
    let URLString: String
    let downloadImageCompletionHandler: (responseObject: AnyObject?, error: NSError?) -> ()
    weak var request: Alamofire.Request?

    init(URLString: String, downloadImageCompletionHandler: (responseObject: AnyObject?, error: NSError?) -> ()) {
        self.URLString = URLString
        self.downloadImageCompletionHandler = downloadImageCompletionHandler
        super.init()
    }

    override func main() {
        let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
        request = Alamofire.download(.GET, URLString, destination).response { (request, response, responseObject, error) in
            if self.cancelled {
                println("Alamofire.download cancelled while downlading. Not proceed.")
            } else {
                self.downloadImageCompletionHandler(responseObject: responseObject, error: error)
            }
            self.completeOperation()
        }
    }

    override func cancel() {
        request?.cancel()
        super.cancel()
    }
}

它覆盖cancel()并尝试取消 Alamofire 请求NSOperation取消。

我使用 KVO 观察者来观察完成NSOperationQueue.

private var testAlamofireContext = 0

class TestAlamofireObserver: NSObject {
    var queue = NSOperationQueue()

    init(delegate: ImageDownloadDelegate) {
        super.init()
        queue.addObserver(self, forKeyPath: "operations", options: .New, context: &testAlamofireContext)
    }

    deinit {
        queue.removeObserver(self, forKeyPath: "operations", context: &testAlamofireContext)
    }

    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) {
        if context == &testAlamofireContext {
            if self.queue.operations.count == 0 {
                println("Image Download Complete queue. keyPath: \(keyPath); object: \(object); context: \(context)")
            }
        } else {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }
    }
}

我开始了这样的下载列表:

func downloadImages() {
    let imgLinks = [
        "https://farm4.staticflickr.com/3925/18769503068_1fc09427ec_k.jpg",
        "https://farm1.staticflickr.com/338/18933828356_4f57420df7_k.jpg",
        "https://farm4.staticflickr.com/3776/18945113685_ccec89d67a_o.jpg",
        "https://farm1.staticflickr.com/366/18333992053_725f21166e_k.jpg",
        "https://farm4.staticflickr.com/3777/18962702032_086453ee7a_k.jpg",
        "https://farm1.staticflickr.com/373/18930501406_4753ac021a_k.jpg",
        "https://farm1.staticflickr.com/283/18772907409_56ffbe573b_k.jpg",
        "https://farm1.staticflickr.com/314/18940901785_b0564b1c9b_o.jpg",
        "https://farm1.staticflickr.com/502/18949263495_88d75d2d2f_k.jpg",
        "https://farm4.staticflickr.com/3912/18938184302_6e0ca9ad31_k.jpg",
        "https://farm1.staticflickr.com/356/18957923475_3dc9df7634_k.jpg",
        "https://farm1.staticflickr.com/378/18925014986_e87feca9c7_o.jpg",
        "https://farm1.staticflickr.com/461/18949863812_ddf700bd03_o.jpg",
        "https://farm1.staticflickr.com/303/18920711216_4684ff4295_k.jpg",
        "https://farm1.staticflickr.com/558/18935058546_fc10d10855_k.jpg",
        "https://farm1.staticflickr.com/384/18955290345_fb93d17828_o.jpg",
        "https://farm1.staticflickr.com/366/18333992053_725f21166e_k.jpg",
        "https://farm4.staticflickr.com/3777/18962702032_086453ee7a_k.jpg",
        "https://farm1.staticflickr.com/373/18930501406_4753ac021a_k.jpg",
        "https://farm1.staticflickr.com/283/18772907409_56ffbe573b_k.jpg",
        "https://farm1.staticflickr.com/314/18940901785_b0564b1c9b_o.jpg",
        "https://farm1.staticflickr.com/502/18949263495_88d75d2d2f_k.jpg",
        "https://farm4.staticflickr.com/3912/18938184302_6e0ca9ad31_k.jpg",
        "https://farm1.staticflickr.com/356/18957923475_3dc9df7634_k.jpg",
        "https://farm1.staticflickr.com/378/18925014986_e87feca9c7_o.jpg",
        "https://farm1.staticflickr.com/461/18949863812_ddf700bd03_o.jpg",
        "https://farm1.staticflickr.com/303/18920711216_4684ff4295_k.jpg",
        "https://farm1.staticflickr.com/558/18935058546_fc10d10855_k.jpg",
        "https://farm1.staticflickr.com/366/18333992053_725f21166e_k.jpg",
        "https://farm4.staticflickr.com/3777/18962702032_086453ee7a_k.jpg",
        "https://farm1.staticflickr.com/373/18930501406_4753ac021a_k.jpg",
        "https://farm1.staticflickr.com/283/18772907409_56ffbe573b_k.jpg",
        "https://farm1.staticflickr.com/314/18940901785_b0564b1c9b_o.jpg",
        "https://farm1.staticflickr.com/502/18949263495_88d75d2d2f_k.jpg",
        "https://farm4.staticflickr.com/3912/18938184302_6e0ca9ad31_k.jpg",
        "https://farm1.staticflickr.com/356/18957923475_3dc9df7634_k.jpg",
        "https://farm1.staticflickr.com/378/18925014986_e87feca9c7_o.jpg",
        "https://farm1.staticflickr.com/461/18949863812_ddf700bd03_o.jpg",
        "https://farm1.staticflickr.com/303/18920711216_4684ff4295_k.jpg",
        "https://farm1.staticflickr.com/558/18935058546_fc10d10855_k.jpg",
        "https://farm4.staticflickr.com/3777/18962702032_086453ee7a_k.jpg",
        "https://farm1.staticflickr.com/373/18930501406_4753ac021a_k.jpg",
        "https://farm1.staticflickr.com/283/18772907409_56ffbe573b_k.jpg",
        "https://farm1.staticflickr.com/314/18940901785_b0564b1c9b_o.jpg",
        "https://farm1.staticflickr.com/502/18949263495_88d75d2d2f_k.jpg",
        "https://farm4.staticflickr.com/3912/18938184302_6e0ca9ad31_k.jpg",
        "https://farm1.staticflickr.com/356/18957923475_3dc9df7634_k.jpg",
        "https://farm1.staticflickr.com/378/18925014986_e87feca9c7_o.jpg",
        "https://farm1.staticflickr.com/461/18949863812_ddf700bd03_o.jpg",
        "https://farm1.staticflickr.com/303/18920711216_4684ff4295_k.jpg",
        "https://farm1.staticflickr.com/558/18935058546_fc10d10855_k.jpg",
        "https://farm1.staticflickr.com/266/18956724112_6e61a743a5_k.jpg"
    ]

    var testAlamofireObserver = TestAlamofireObserver()
    testAlamofireObserver!.queue.maxConcurrentOperationCount = 5

    for imgLink in imgLinks {
        let operation = DownloadImageOperation(URLString: imgLink) {
            (responseObject, error) in

            if responseObject == nil {
                // handle error here
                println("failed: \(error)")
            } else {
                println("\(responseObject?.absoluteString) downloaded.")
            }
        }
        testAlamofireObserver!.queue.addOperation(operation)
    }
}

如果队列完成而没有收到任何取消,则日志输出应为:

2015-06-22 17:11:04.206 RSS Wallpaper Switchr[46250:714702] Optional(Optional("https://farm1.staticflickr.com/461/18949863812_ddf700bd03_o.jpg")) downloaded.
...
...
...
2015-06-22 17:11:56.979 RSS Wallpaper Switchr[46250:714702] Optional(Optional("https://farm1.staticflickr.com/461/18949863812_ddf700bd03_o.jpg")) downloaded.
2015-06-22 17:11:56.979 RSS Wallpaper Switchr[46250:714702] Image Download Complete queue. keyPath: operations; object: <NSOperationQueue: 0x6180002354a0>{name = 'NSOperationQueue 0x6180002354a0'}; context: 0x000000010007eb70

如果队列收到cancelAllOperations(),日志输出应该是:

2015-06-22 17:16:29.691 RSS Wallpaper Switchr[46467:720630] Optional(Optional("https://farm1.staticflickr.com/366/18333992053_725f21166e_k.jpg")) downloaded.
2015-06-22 17:16:32.632 RSS Wallpaper Switchr[46467:720630] Alamofire.download cancelled while downlading. Not proceed.
...
...
2015-06-22 17:16:32.642 RSS Wallpaper Switchr[46467:720630] Alamofire.download cancelled while downlading. Not proceed.
2015-06-22 17:16:32.643 RSS Wallpaper Switchr[46467:720630] Image Download Complete queue. keyPath: operations; object: <NSOperationQueue: 0x600000024c20>{name = 'NSOperationQueue 0x600000024c20'}; context: 0x000000010007eb70

然而,如果我改变了maxConcurrentOperationCount如上所述的非默认值,并且队列接收cancelAllOperations(),日志变成:

2015-06-22 17:17:56.427 RSS Wallpaper Switchr[46606:722523] Optional(Optional("https://farm4.staticflickr.com/3777/18962702032_086453ee7a_k.jpg")) downloaded.
2015-06-22 17:17:58.675 RSS Wallpaper Switchr[46606:722523] Alamofire.download cancelled while downlading. Not proceed.
...
...
2015-06-22 17:17:58.677 RSS Wallpaper Switchr[46606:722523] Alamofire.download cancelled while downlading. Not proceed.
2015-06-22 17:17:58.678 RSS Wallpaper Switchr[46606:722720] Image Download Complete queue. keyPath: operations; object: <NSOperationQueue: 0x608000424ee0>{name = 'NSOperationQueue 0x608000424ee0'}; context: 0x000000010007eb70
2015-06-22 17:17:58.678 RSS Wallpaper Switchr[46606:722560] Image Download Complete queue. keyPath: operations; object: <NSOperationQueue: 0x608000424ee0>{name = 'NSOperationQueue 0x608000424ee0'}; context: 0x000000010007eb70
2015-06-22 17:17:58.678 RSS Wallpaper Switchr[46606:722574] Image Download Complete queue. keyPath: operations; object: <NSOperationQueue: 0x608000424ee0>{name = 'NSOperationQueue 0x608000424ee0'}; context: 0x000000010007eb70
2015-06-22 17:17:58.678 RSS Wallpaper Switchr[46606:722719] Image Download Complete queue. keyPath: operations; object: <NSOperationQueue: 0x608000424ee0>{name = 'NSOperationQueue 0x608000424ee0'}; context: 0x000000010007eb70
2015-06-22 17:17:58.678 RSS Wallpaper Switchr[46606:722721] Image Download Complete queue. keyPath: operations; object: <NSOperationQueue: 0x608000424ee0>{name = 'NSOperationQueue 0x608000424ee0'}; context: 0x000000010007eb70
2015-06-22 17:17:58.678 RSS Wallpaper Switchr[46606:722572] Image Download Complete queue. keyPath: operations; object: <NSOperationQueue: 0x608000424ee0>{name = 'NSOperationQueue 0x608000424ee0'}; context: 0x000000010007eb70

The KVO observeValueForKeyPath从多个不同的线程执行。线程的数量可以是可变的。这将导致KVO的完成函数被执行多次。如果我不更改默认值,这种情况就不会发生maxConcurrentOperationCount或不request?.cancel() for Alamofire.Request.

为什么我关心 KVO 完成函数的多次执行?我的目的是启动一个下载队列,当足够的下载完成时,取消剩余的操作,即使是未启动的或正在下载的操作,然后为下载做一些事情。完成函数应该只执行一次,两个因素 (1) 改变了默认值maxConcurrentOperationCount(2) 不request?.cancel() for Alamofire.Request可能与此有关。我想知道为什么以及如何纠正这个问题。


我不觉得你描述的多重 KVN 行为有那么令人惊讶。文档中没有任何内容表明,当取消所有操作时,单个 KVN 会operations将导致。事实上,人们可以安全地推断出您描述的行为应该是预期的(因为它不会抢先杀死所有这些工作线程,而是发送一个cancel向每个操作发送消息,每个操作负责在自己的时间内响应该消息;我没想到operations直到操作最终实际完成为止)。

就我个人而言,我建议完全废除这种观察者模式。您的代码不应取决于是否NSOperationQueue是否立即删除所有操作。相反,我建议您依靠现有的downloadImageCompletionHandler关闭,无论请求是否完成都会调用它。只需要关闭看看error反对弄清楚它是否被取消或是否因其他原因失败。


如果您的目的是知道所有这些操作何时完成,我不会依赖operationsKVN。相反,我可能会创建一个完成操作,具体取决于所有其他请求:

let completionOperation = NSBlockOperation() {                    // create completion operation
    // do whatever you want here
}

for imgLink in imgLinks {
    let operation = DownloadImageOperation(URLString: imgLink) { responseObject, error in
        if error != nil {
            if error!.code == NSURLErrorCancelled && error!.domain == NSURLErrorDomain {
                println("everything OK, just canceled")
            } else {
                println("error=\(error)")
            }
        }
        if responseObject != nil {
            println("\(responseObject?.absoluteString) downloaded.")
        }
    }

    completionOperation.addDependency(operation)                 // add dependency

    testAlamofireObserver!.queue.addOperation(operation)
}

NSOperationQueue.mainQueue().addOperation(completionOperation)   // schedule completion operation on some other queue (so that when I cancel everything on that other queue, I don't cancel this, too)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

取消封装在 NSOperation 中的 Alamofire 请求会导致多个 KVO? 的相关文章

  • 为 Linux 编译 Objective-C 应用程序(API 覆盖范围)

    我可能在这里问一些奇怪的问题 但我不确定从哪里开始 问题是我正在考虑使用 Obj C 和 Foundation 类在 Mac 上编写一个命令行工具 但存在一个非常大的风险 那就是我希望能够为不同的 Linux 发行版编译它 以便将来作为服务
  • 如何将渐变应用于 iOS Swift 应用程序的背景视图

    我正在尝试应用渐变作为视图 故事板的主视图 的背景颜色 代码运行 但没有任何变化 我正在使用 xCode Beta 2 和 Swift 这是代码 class Colors let colorTop UIColor red 192 0 255
  • 在 Swift 中获取 UIImage 的主颜色

    我正在尝试在 Swift 中获取 UIImage 的主颜色 并尝试移植这段代码 https stackoverflow com questions 13694618 objective c getting least used and mo
  • 对于 Swift 中的计算器

    只是要警告你 我是 Swift 的新手 我仍在适应它的工作原理 我一直在尝试在课堂上完成这个计算器项目 问题是 我需要练习简化代码 现在 当按下数字按钮时 我将其保存在这样的数组中 IBAction func buttonPressed s
  • Swift 中的“funcobserveValueForKeyPath(keyPath:NSString,object:AnyObject,change:NSDictionary,context:Void)”问题

    我已经为 AVPlayer 添加了一个观察者 如下所示 self audioPlayer addObserver self forKeyPath currentItem status options NSKeyValueObservingO
  • 如何在 SwiftUI 中将阴影应用于内部视图?

    我在周围添加了阴影VStack其中包含我的两个文本字段和一个提交按钮 然而 阴影也被应用到了文本框内的两个文本字段 VStack 我在这里缺少什么导致这种情况发生吗 我尝试添加shadow radius 0 在文本字段上 但它不会改变任何内
  • 在 Cocoa OS X AVPlayer 中播放 HLS (m3u8) - Swift

    基本上我正在尝试在 Cocoa Swift 中使用 AVPlayer 播放 m3u8 HLS Live Stream 我对这门语言比较陌生 所以基本上掌握了一些示例代码 http qiita com ono matope items 23d
  • 在没有预览窗口的情况下使用 AVCaptureVideoDataOutputSampleBufferDelegate

    我正在开发一个基于 Swift 的 macOS 应用程序 我需要捕获视频输入 但不将其显示在屏幕上 而不是显示视频 我想将缓冲的数据发送到其他地方进行处理 并最终显示它在 a 中的一个物体上SceneKit scene 我有一个Camera
  • 在 OS X 上创建和使用静态库

    好的 我正在尝试创建一个 Cocoa 库 静态 并使用 但我不断收到错误 我创建了一个超基本的静态库 TSXLib 其中仅包含一个额外的类 import
  • 如何将 UILabel 的值绑定到实例变量?

    我是 mac objective c 的新手 我的问题是 我想知道是否可以将 UILabel 文本绑定到变量 而不必在值更改时手动设置文本 例如 在 Mac OS 上 当我打开新的 Finder 窗口并删除文件时 任务栏中的全局可用空间就会
  • UIButton的高亮状态由什么控制事件开始和结束

    我正在创建类似钢琴的视图UIButton作为钢琴键 什么UIControlEvents当按钮获得和失去突出显示状态时 我应该监听以获得回调吗 我试图创建子类UIButton并添加属性观察者highlighted并且运行良好 然而 有时我需要
  • 减少 CoreData 的调试输出?

    我正在开发一个使用 CoreData 的 iOS macOS 项目 它工作正常 但它会向控制台输出大量调试信息 这使得控制台无法使用 因为我的打印语句隐藏在所有与 CoreData 相关的内容中 我有一个非常简单的 CoreData 设置
  • 如何让按钮闪烁?

    我试图在扫描正确时将按钮的颜色 只是闪烁 闪烁 更改为绿色 在出现问题时将按钮的颜色更改为红色 我可以用这样的视图来做到这一点 func flashBG UIView animateWithDuration 0 7 animations s
  • 根据 iOS 版本使用不同的类实现?

    iOS 11 最近添加了一个我想使用的新功能 但我仍然需要支持旧版本的 iOS 有没有一种方法可以将同一个类编写两次 并让较新版本的 iOS 使用该类的一个版本 而旧版本的 iOS 使用另一个版本 注 最初我用的是if available
  • 关闭捕获上下文 Swift

    当我尝试更改闭包中的变量时出现此错误 A C function pointer cannot be formed from a closure that captures context 是否有解决方法或者仍然可以更改闭包内的变量 My C
  • 根据内容自动更改单元格高度 - Swift

    在 Swift 中使用 UITableView 有人可以帮我根据标签 图片和描述自动更改单元格的高度吗 所有信息都正确传递 我只需要帮助格式化它 我尝试使用调整它cell frame size height 但这没有效果 我可以更改故事板中
  • 在 SwiftUI 中使用可观察对象切换视图

    我正在练习尝试使用 SwiftUI 中的可观察对象切换视图 但我的代码无法正常工作 我知道我可以用 State 来做到这一点 但我想用可观察的对象来实现这一点 当我单击内容视图中的图像时 图像不会改变 有人能帮我吗 内容视图 swift i
  • 在可可中将 NSMutableArray 写入文件时出现问题

    一个真正的初学者问题 我有一个 NSView 子类 在其中创建一个包含 NSValues 的 NSMutableArray 当我想使用 writetofile atomatically 将数组写入文件时 文件已创建 但它不包含可变数组所包含
  • 在 Object 子类及其自己的子类上实现ignoreProperties()

    我是领域新手 我正在使用继承自 Object 的基类以及该基类的自定义子类创建模型 我的模型要求基类通过覆盖静态来声明一些属性被忽略ignoredProperties 方法 当尝试在某些基类子类上重写该方法时 我收到一个 Swift 编译器
  • Fitbit oauth2 公共 API 停止工作。给出错误 - 抱歉,这不是你..是我们

    几个月前 我准备了一个关于 Fitbit oauth2 公共 API 的演示 其中我使用特定用户登录并获取他的活动 一切正常 但最近 我打开演示并尝试使用同一用户登录 但它没有登录并反复出现此错误 我尝试更改在 Fitbit 上注册的演示应

随机推荐