1

I try to create simple button, with handler of it's event in another class. So i write something like that:

var handler = Handler()
var btn = UIButton(...)
...
btn.addTarget(handler, "onClick", UIControlEvents.TouchDown)
view.addSubview(btn)

And i declare class Handler:

class Handler : UIViewController {
    func onClick() {
        NSLog("Success!")    
    }
}

But when i click on button, my program crash with some error, and highlight this standard, auto-generated code:

class AppDelegate: UIResponder, UIApplicationDelegate { ----- Thread 1: EXC_BAD_ACCESS(code=2, address=0xc)

So can somebody explain how to use handler for button's events, from another than self class?

UPD: It cause same error even if i use next way:

class Handler : UIViewController {
    func addButton() -> UIButton {
        *initialize button*
        btn.addTarget(self, "onClick", .TouchDown)
        return btn
    }
    func onClick() { NSLog("Success") }
}
....
view.addSubview(Handler().addButton())

Solution: The reason was in creating class for target. I create it in viewDidLoad() for my example, and when method finish his execution, object was deleted. It needs to create that target object in more general context, like class field or smth.

Vitaliy L
  • 572
  • 4
  • 20
  • Try deleting UIControlEvent or replace it with UIControlEvents. – Daan Lemmen Jul 08 '14 at 14:40
  • Oh, sorry, it's my typing mistake. There is UIControlEvents.TouchDown of course. Edit answer. – Vitaliy L Jul 08 '14 at 14:42
  • For what it's worth, general button actions should be on `.TouchUpInside` not on `.TouchDown` Buttons are expected to act when you release inside them, not at the moment of touch. – David Berry Jul 08 '14 at 16:46
  • 1
    In looking at your code, it looks likely that you're not keeping your reference to handler around, so it's being released. The button stays around because you add it to the view hierarchy. Then when you touch the button, you're trying to invoke a method on an object that's been released. – David Berry Jul 08 '14 at 16:49
  • I'm also not sure why `Handler` is declared to be a subclass of `UIViewController` – David Berry Jul 08 '14 at 16:49
  • Problem was in reference, as you said. Thanks for help! – Vitaliy L Jul 09 '14 at 08:20

0 Answers0