我一直在尝试创建 NSTextFieldCell 的子类以与自定义 NSTextField (使用 Swift)一起使用。但是,尝试复制子类单元格时,我的代码会中断。我的基本代码是
class XYTextFieldCell: NSTextFieldCell {
var borderColor = NSColor.init(red: 0.5, green: 0.5, blue: 0.5, alpha: 1)
override init(imageCell image: NSImage?) {
super.init(imageCell: image)
}
override init(textCell aString: String) {
super.init(textCell: aString)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
Swift.print("Deinit XYTextFieldCell: \(unsafeAddressOf(self))")
}
}
在 AppDelegate 中(尝试在一个小应用程序中模拟崩溃),我有
func applicationDidFinishLaunching(aNotification: NSNotification) {
let textFieldCell = XYTextFieldCell.init(textCell: "Test")
Swift.print("TextFieldCell: \(unsafeAddressOf(textFieldCell))")
print("textFieldCell.color: \(unsafeAddressOf(textFieldCell.borderColor))")
copyTextFieldCell(textFieldCell)
}
func copyTextFieldCell(textFieldCell: XYTextFieldCell) {
Swift.print("TextFieldCell (param): \(unsafeAddressOf(textFieldCell))")
let copy = textFieldCell.copy() as! XYTextFieldCell
Swift.print("TextFieldCell (copy): \(unsafeAddressOf(copy))")
print("copy.color: \(unsafeAddressOf(copy.borderColor))")
}
该应用程序崩溃
[NSColorSpaceColor release]: message sent to deallocated instance 0x600000075240
全输出为
TextFieldCell: 0x00006080000a61e0
textFieldCell.color: 0x0000608000074840
TextFieldCell (param): 0x00006080000a61e0
TextFieldCell (copy): 0x00006080000a62a0
copy.color: 0x0000608000074840
Deinit XYTextFieldCell: 0x00006080000a62a0
Deinit XYTextFieldCell: 0x00006080000a61e0
2015-10-09 16:52:35.043 Test[86949:4746488] *** -[NSColorSpaceColor release]: message sent to deallocated instance 0x608000074840
复制后似乎没有正确保留borderColor(并且正在被双重释放)。然后我尝试添加复制重载以尝试强制复制边框颜色。
override func copyWithZone(zone: NSZone) -> AnyObject {
let myCopy = super.copyWithZone(zone) as! XYTextFieldCell
myCopy.borderColor = borderColor.copyWithZone(zone) as! NSColor
return myCopy
}
但是,它仍然会因相同的错误而崩溃
TextFieldCell: 0x00006080000ab4c0 textFieldCell.color: 0x00006080000769c0
TextFieldCell (param): 0x00006080000ab4c0
TextFieldCell (copy): 0x00006080000ab520
copy.color: 0x00006080000769c0
Deinit XYTextFieldCell: 0x00006080000ab520
Deinit XYTextFieldCell: 0x00006080000ab4c0
2015-10-09 16:54:54.248 Test[87031:4749016] *** -[NSColorSpaceColor release]: message sent to deallocated instance 0x6080000769c0
我可以通过在 copyWithZone 中初始化一个新的 XYTextFieldCell 来避免崩溃:(而不是调用 super.copyWithZone)。但是,这意味着我也必须手动将所有超类定义的属性重新分配给我的副本。
有没有办法正确复制 NSTextFieldCell ,这样它就不会双重释放我的子类属性。从 NSButtonCell 子类化时,我也注意到了这种行为。但是,如果我不从任何一个继承(XYTextFieldCell 是一个根 Swift 类),那么它工作正常。谢谢