Amanda Amanda - 1 year ago 188
Swift Question

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_.AppDelegate add:]: unrecognized selector

I created a storyboard called Main.storyboard and created a AddBtnViewController with storyboard ID "addBtnVC". In the App Delegate, I initialized a tab bar with three view controllers programmatically. For one of tab bar view controllers, I created an add button that would transition to the AddBtnViewController programmatically. However, I received this error:

uncaught exception 'NSInvalidArgumentException', reason: '-[_.AppDelegate add:]: unrecognized selector sent to instance 0x7f91cb422a30'

My code:

class AppDelegate: UIResponder, UIApplicationDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//Make add btn for View Controller 1 of Navigation Bar
let addBtn = UIButton(frame: CGRectMake(0, 0, 30, 30))
addBtn.addTarget(self, action: #selector(ViewController1.add), forControlEvents: .TouchUpInside)

let rightBarButton = UIBarButtonItem()
rightBarButton.customView = addBtn
NavController.navigationBar.topItem?.rightBarButtonItem = rightBarButton

return true

class ViewController1: UIViewController {
let addBtnVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("addBtnVC")

func add(sender: UIButton!) {
if let addBtnVC = storyboard!.instantiateViewControllerWithIdentifier("addBtnVC") as? AddBtnViewController {
presentViewController(addBtnVC, animated: true, completion: nil)

How do I fix this error?

Answer Source

You set the target of the button action to self which represents the AppDelegate class.

The selector of the button action must be in the same class as the target but it isn't. That's what the error message says. Further the signature of the selector is wrong because it takes one parameter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download