NSOperation属性覆盖(isExecuting/isFinished) [英] NSOperation property overrides (isExecuting / isFinished)

查看:190
本文介绍了NSOperation属性覆盖(isExecuting/isFinished)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift中将NSOperation子类化,并且需要覆盖isExecutingisFinished属性,因为我覆盖了start方法.

I am subclassing NSOperation in Swift and need to override the isExecuting and isFinished properties since I am overriding the start method.

我遇到的问题是如何保留键值观察(KVO),同时又能够覆盖这些属性.

The problem I run into is how to preserve key-value observing (KVO) while also being able to override these properties.

通常在Obj-C中,这很容易在类扩展JSONOperation ()定义中将属性重新声明为readwrite.但是,我在Swift中看不到这种功能.

Normally in Obj-C this would be rather easy to redeclare the properties as readwrite in the class extension JSONOperation () definition. However, I don't see this same capability in Swift.

示例:

class JSONOperation : NSOperation, NSURLConnectionDelegate
{
    var executing : Bool
    {
        get { return super.executing }
        set { super.executing } // ERROR: readonly in the superclass
    }

    // Starts the asynchronous NSURLConnection on the main thread
    override func start()
    {
        self.willChangeValueForKey("isExecuting")
        self.executing = true
        self.didChangeValueForKey("isExecuting")

        NSOperationQueue.mainQueue().addOperationWithBlock(
        {
            self.connection = NSURLConnection(request: self.request, delegate: self, startImmediately: true)
        })
    }
}

这是我想出的解决方案,但是它感觉很丑陋,很笨拙:

So here is the solution I have come up with, but it feels awfully ugly and hacky:

var state = Operation()

struct Operation
{
    var executing = false
    var finished = false
}

override var executing : Bool
{
    get { return state.executing }
    set { state.executing = newValue }
}

override var finished : Bool
{
    get { return state.finished }
    set { state.finished = newValue }
}

请告诉我还有更好的方法.我知道我可以制作一个var isExecuting而不是整个struct,但是然后我有两个名称相似的属性,它们引入了歧义性,并且使其可公开写入(我不希望这样做).

Please tell me there is a better way. I know I could make a var isExecuting instead of the whole struct, but then I have two similarly named properties which introduces ambiguity and also makes it publicly writable (which I do not want).

我该怎么做一些访问修饰符关键字...

Oh what I would do for some access modifier keywords...

推荐答案

摘自快速书:

通过在子类属性重写中同时提供getter和setter,可以将继承的只读属性呈现为读写属性.

You can present an inherited read-only property as a read-write property by providing both a getter and a setter in your subclass property override.

我想您会发现这可行:

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

这篇关于NSOperation属性覆盖(isExecuting/isFinished)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆