3

I've subclassed NSOperation, to perform an asynchronous operation. But I'm not clear on how I declare the operation to be finished. I overrided it as follows, but it just doesn't seem right that I should be manually calling willChangeValueForKey and didChangeValueForKey.

private var downloadComplete = false

override var finished: Bool {
    get { return self.downloadComplete }
    set {
        willChangeValueForKey("isFinished")
        self.downloadComplete = newValue
        didChangeValueForKey("isFinished")
    }
}
Andrew
  • 7,693
  • 11
  • 43
  • 81
  • That is the way to do it. If you override the setter you have to trigger kvo by yourself and that is what you have done in the above code which looks perfectly fine. Either override it or simple leave it and set finished by yourself. – Sandeep Aug 17 '15 at 09:55
  • Not sure what this has to do with objective-c. – Jasper Aug 17 '15 at 09:55
  • 1
    @Jasper It's using an Objective-C technique in Swift. But I accept that maybe the tag isn't relevant, and removed it. – Andrew Aug 17 '15 at 09:57
  • @GeneratorOfOne That last thing you said - that's what I want to do. "Leave it and set finished by yourself". I want to do that. How else can I do that, because `finished` is readonly. – Andrew Aug 17 '15 at 09:58
  • Use a separate variable to track the state isReady, isExecuting, isFinished, isCancelled and use kvo method to trigger the change for that variable https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSKeyValueObserving_Protocol/#//apple_ref/occ/clm/NSObject/automaticallyNotifiesObserversForKey: and you will be able to have the same effect – Sandeep Aug 17 '15 at 10:01
  • Or something like this gist https://gist.github.com/skoirala/553a48a1963ff7f54ccb – Sandeep Aug 17 '15 at 10:04

0 Answers0