shah.shah shah.shah - 1 year ago 44
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

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() {
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(
). What's the problem? What should I do to fix it?

Answer Source

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.