2016-07-03 26 views
2

我想通過繼承將存儲的屬性添加到NSBezierPath中。但是下面的代碼崩潰遊樂場:爲什麼NSBezierPath這個簡單的子類會使我的OSX 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() 

操場錯誤(下)似乎表明與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

嗯...閱讀[這個其他答案](http://stackoverflow.com/questions/29867782/uibezierpath-subclass-initializer)這聽起來像繼承NSBezierPa這可能是一個**糟糕的主意。也許我必須去一個包裝 - 這是一個恥辱,因爲它使得代碼更清晰:( –

+0

這也是一個令人討厭的崩潰...我有點驚訝Xcode不處理它更好 –

+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

編輯:您可以創建一組方法和你INIT-內使用方法:

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

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

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

但我不想添加一個方法,我想添加一個存儲的屬性... –

+0

是的,但他們都是相關的,因爲你的問題是來自任何一個領域。更新的答案 – tymac

+0

請給出一個具體的例子,說明你的建議如何用於通過繼承NSBezierPath來添加存儲的屬性。 –