shah.shah shah.shah - 6 months ago 7
Swift Question

Trying to access property of a class which subclasses a cocoa class gives run-time error

I made a customized button type(class) that inherits from

NSButton
and has some additional methods as well, but when I try to access the methods that I declared myself, I get a run-time error. Here's my code:

import Cocoa

class MCButton: NSButton {
func testFunc()->Bool {
return true
}
}

class ViewController: NSViewController {
@IBOutlet weak var button: MCButton!

override func viewDidLoad() {
super.viewDidLoad()
if button.testFunc() { //Thread 1: EXC_BAD_ACCESS(code=2, address=0x608000264600)
button.title = "Hi!"
}
}

}


Note that I don't have any problems when I only use the methods declared in the superclass(
NSButton
). What's the problem? What should I do to fix it?

Answer

You have to correctly set the button's class in the InterfaceBuilder. It probably has the predefined value set, which is NSButton. You have to set it to MCButton instead.

Only then you actually get a reference to a correct instance of one of those MCButtons.

Comments