为什么这个简单的NSBezierPath子类会崩溃我的OSX Playground?

时间:2016-07-03 20:22:52

标签: swift macos subclassing nsbezierpath

我试图通过子类化将存储的属性添加到NSBezierPath。但是,以下代码崩溃了Playground:

import Cocoa

class MyNSBezierPath: NSBezierPath {

    private var someProperty: Bool

    override init() {
        someProperty = false
        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        self.someProperty = false
        super.init(coder: aDecoder)
    }
}

// the following line causes the Playground to fully crash
let somePath = MyNSBezierPath()

Playground错误(下面)似乎表明NSCoder存在问题,但我认为只需将调用传递给超类就可以了。我做错了什么?

UNCAUGHT EXCEPTION (NSInvalidUnarchiveOperationException): 
*** - [NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class
(__lldb_expr_22.MyNSBezierPath) for key (root); 
the class may be defined in source code or a library that is not linked
UserInfo: { "__NSCoderInternalErrorCode" = 4864;}
Hints: None

1 个答案:

答案 0 :(得分:1)

您可以创建一个扩展来向NSBezierPath添加方法。

#if os(iOS)
typealias OSBezierPath = UIBezierPath
#else
typealias OSBezierPath = NSBezierPath

extension OSBezierPath {
    func addLineToPoint(point:CGPoint) {
        self.lineToPoint(point)
    }
}
#endif

或者您可以通过使用初始化程序调用lineToPoint来使用OSBezierPath。

#if os(iOS)
class OSBezierPath: UIBezierPath {
    func lineToPoint(point:CGPoint) {
        self.addLineToPoint(point)
    }
}
#else
typealias OSBezierPath = NSBezierPath
#endif

Apple Swift

中的一些代码

当然,这不是同一个功能,但我正在使用typealias OSBezierPath = UIBezierPath

向您展示Apple

编辑:您可以创建一个集合方法并在init-Method中使用它:

class SomeClass {
var someProperty: AnyObject! {
    didSet {
        //do something
    }
}

init(someProperty: AnyObject) {
    setSomeProperty(someProperty)
}

func setSomeProperty(newValue:AnyObject) {
    self.someProperty = newValue
}
}