【问题标题】:Why does this simple subclass of NSBezierPath crash my OSX Playground?为什么 NSBezierPath 的这个简单子类会使我的 OSX Playground 崩溃?
【发布时间】:2016-07-03 20:22:52
【问题描述】:

我正在尝试通过子类化将存储属性添加到 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

【问题讨论】:

  • 嗯...阅读this other answer 听起来子类化 NSBezierPath 可能是一个的想法。也许我将不得不使用包装器 - 这很遗憾,因为它使代码不那么清晰:(
  • 这也是一个令人讨厌的崩溃...我有点惊讶 Xcode 不能更好地处理它。
  • 你和我都...

标签: swift macos subclassing nsbezierpath


【解决方案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的一些代码

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

编辑:您可以创建一个 set Method 并在您的 init-Method 中使用它:

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

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

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

【讨论】:

  • 是的,但如果您的问题来自这些领域中的任何一个,它们都是相关的。请参阅我的新更新答案。
  • 请给出一个具体示例,说明您的建议如何用于通过继承 NSBezierPath 来添加存储属性。
猜你喜欢
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 2012-11-29
  • 1970-01-01
  • 2010-11-23
  • 2019-01-13
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多