I’m still crashing my app with the UIBarButtonItem:
I’ve tried 3 several ways I found here in previous topics, and none of them have worked out. I’m new to Swift and I really don’t know what could be causing the problem, before it worked just fine…
The 3 several ways I tried, which 1 is the original code:
1)
let btnDone = UIBarButtonItem(barButtonSystemItem: .done, target: MyViewController.self, action: #selector(onBtnDoneTap))
@objc private func onBtnDoneTap() { code to be executed on tap... }
2)
let btnDone = UIBarButtonItem(barButtonSystemItem: .done, target: MyViewController.self, action: #selector(onBtnDoneTap(sender:)))
@objc private func onBtnDoneTap(sender: UIBarButtonItem) { code to be executed on tap... }
3)
let btnDone = UIBarButtonItem(barButtonSystemItem: .done, target: MyViewController.self, action: #selector(onBtnDoneTap(_:)))
@objc private func onBtnDoneTap(_ sender: UIBarButtonItem) { code to be executed on tap... }
All crashed on the following line:
UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(appDelegateClass))
Thread 1: "+[App.MyViewController onBtnDoneTap]: unrecognized selector sent to class 0x1051c38b0"
With the following errors in the output window:
[13122:7952368] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[App.MyViewController onBtnDoneTap]: unrecognized selector sent to class 0x1051c38b0'
libc++abi: terminating with uncaught exception of type NSException dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[App.MyViewController onBtnDoneTap]: unrecognized selector sent to class 0x1051c38b0' terminating with uncaught exception of type NSException (lldb)
Thanks for your help!
>Solution :
Instead of MyViewController.self as the action target, use self:
let btnDone = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onBtnDoneTap))
This means that the target is not the class MyViewController but a specific MyViewController instance.