Unexpectedly found nil when sending data with Delegates and protocols pattern - swift

I have 2 viewcontrollers, firstVC and secondVC. I want to send data from the first one to update the secondVC's variable and UI.
I want to send tableView's indexPath.row with delegate when it is tapped in didSelectRowAt.
This is what I try, but when selecting a row the app crashes with error:
Unexpectedly found nil while implicitly unwrapping an Optional value
I tried to debug and saw that the delegate is nil, even if I put a method to make the delegate firstVC.
SecondVC:
func setupDelegate() {
let FirstVC = storyboard?.instantiateViewController(identifier: "FirstVC") as! FirstVC
FirstVC.selectionDelegate = self
}
}
extension SecondVC: setSelectionDelegate {
//this is never executed
func didChoose(index: Int) {
lbl.text = String(index)
}
}
FirstVC:
protocol setSelectionDelegate {
func didChoose(index: Int)
}
var selectionDelegate: setSelectionDelegate!
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let secondVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "secondVC") as? secondVC
secondVC?.setupDelegate()
self.selectionDelegate.didChoose(index: indexPath.row)
}

Each time you call instantiateViewController explicitly, you get a new instance of the view controller and this is NOT the same instance that you are seeing in your device/simulator.
With storyboard segues ( embed or present modally... ) you have override prepare(...) function to get a reference to desired view controller instance.

Related

How to dismiss UIViewController from UITableViewCell

I need to dismiss ViewController from the corresponding TableViewCell, but I'm getting an error message, "Value of type 'TableViewCell' has no member 'dismiss'"
self.dismiss(animated: true, completion: nil)
How can I dismiss the ViewController from the corresponding TableViewCell
If you just want the solution and don't really care about the structure of the application, the following will work. As the other guy mentioned, this probably isn't the best way to structure your application.
Make a delegate to the TableViewCell.
protocol TableViewDismissDelegate {
func dismissViewController()
}
class YourTableViewClass {
var delegate: TableViewDismissDelegate?
...
}
In your table view delegate:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = mainTableView.dequeueReusableCell(withIdentifier: YourTableViewClass.identifier, for: indexPath) as! YourTableViewClass
cell.delegate = self
return cell
}
Make sure your view controller conforms to your protocol:
extension YourViewController: TableViewDismissDelegate {
func dismissViewController() {
self.dismiss(animated: true, completion: nil)
}
}
You cannot say self.dismiss in a UITableViewCell, as dismiss is a UIViewController command, and a UITableViewCell is not a UIViewController.
What I like to do in this situation is get a reference to the UIViewController so that I can tell it to dismiss. To do so, I create a UIResponder extension, like this:
extension UIResponder {
func next<T:UIResponder>(ofType: T.Type) -> T? {
let r = self.next
if let r = r as? T ?? r?.next(ofType: T.self) {
return r
} else {
return nil
}
}
}
That extension just walks up the responder chain looking for an instance of any class we care to name. So now self.next(ofType: UIViewController.self) is the view controller, and we can tell it to dismiss.
(There are plenty of other solutions, but that's just a solution that I happen to like.)
It may be argued, however, that you should never have gotten yourself in this situation in the first place. It is no business of a UITableViewCell to be telling anyone to dismiss anything. This is a violation of model-view-controller principles. You should probably be looking at a completely different architecture here.

De-initialzing a ViewController after dismissal?

I have two viewControllers in my App, the code for the first viewController is as illustrated below:
import UIKit
class firstViewController: UIViewController {
// The below two variables will be passed from the firstViewController to the secondViewController then back again from the secondViewController to the firstViewController:
var selectedRowValue: Int = 0
var selectedSectionValue: Int = 0
let main = UIStoryboard(name: "Main", bundle: nil)
lazy var secondViewController = main.instantiateViewController(withIdentifier: "secondViewController")
override func viewDidLoad() {
super.viewDidLoad()
}
// The below function will be triggered when the user tap on a specific tableView cell detailClosure icon. This is when the needed data get sent from this viewController to the secondViewController:
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let secondViewControllerProperties = secondViewController as! secondViewController
secondViewControllerProperties.receivedSelectedSectionValueFromFirstVc = indexPath.section
secondViewControllerProperties.receivedSelectedRowValueFromFirstVc = indexPath.row
// The below is the relevant content of a UILabel inside the tapped tableView cell by the user that get send to the secondViewController for it to be displayed as its NavigationBar title:
secondViewControllerProperties.selectedUniversalBeamSectionDesignation = arrayWithAllDataRelatedToUbsSections.filter({ $0.sectionSerialNumber == "\(arrayWithAllSectionsSerialNumbers[indexPath.section])" }).map({ $0.fullSectionDesignation })[indexPath.row]
self.present(secondViewControllerProperties, animated: true, completion: nil)
}
}
// The below extension inside the firstViewController is used to pass data back from the secondViewController to the firstViewController:
extension firstViewController: ProtocolToPassDataBackwardsFromSecondVcToFirstVc {
func dataToBePassedUsingProtocol(passedSelectedTableSectionNumberFromPreviousVc: Int, passedSelectedTableRowNumberFromPreviousVc: Int) {
self.selectedRowValue = passedSelectedTableRowNumberFromPreviousVc
self. selectedSectionValue = passedSelectedTableSectionNumberFromPreviousVc
}
}
Below is the code inside the second view controller:
import UIKit
class secondViewController: UIViewController {
weak var delegate: ProtocolToPassDataBackwardsFromSecondVcToFirstVc?
// The below variables get their values when the data get passed from the firstViewController to the secondViewController:
var receivedSelectedRowValueFromFirstVc: Int = 0
var receivedSelectedSectionValueFromFirstVc: Int = 0
var selectedUniversalBeamSectionDesignation: String = ""
// Inside the below navigationBar declaration, its labelTitleText will depend on the tapped tableViewCell by the user inside the firstViewController:
lazy var navigationBar = CustomUINavigationBar(navBarLeftButtonTarget: self, navBarLeftButtonSelector: #selector(navigationBarLeftButtonPressed(sender:)), labelTitleText: "UB \(selectedUniversalBeamSectionDesignation)", navBarDelegate: self)
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(navigationBar)
}
// The below gets triggered when the user hit the back button inside the navigationBar of the secondViewController. This is where using the Protocol data get passed back to the firstViewController:
extension secondViewController: UINavigationBarDelegate {
#objc func navigationBarLeftButtonPressed(sender : UIButton) {
if delegate != nil {
delegate?.dataToBePassedUsingProtocol(passedSelectedTableSectionNumberFromPreviousVc: self.selectedTableSectionNumberFromPreviousViewController, passedSelectedTableRowNumberFromPreviousVc: self.selectedTableRowNumberFromPreviousViewController)
}
dismiss(animated: true) {}
}
}
However, what I am noticing is whenever the secondViewController gets dismissed when the user hit on the back button inside the navigationBar of the secondViewController. The secondViewController does not get de-initialized, and therefore, whenever I press on a different cell inside the tableView inside the firstViewController, the navigationBar title that gets displayed inside the secondViewController is still the same as the one displayed when I pressed the first time. Since the secondViewController did not get de-initialzied and thus, I am seeing the same values as the first time it got initialized.
My question is how to de-initialize the secondViewController when it gets dismissed, so that every time I tap on a different cell inside the tableView inside the firstViewController a new secondViewController gets initialized?
Your code generates secondViewController once and reuses it (it's a property).
lazy var secondViewController = main.instantiateViewController(withIdentifier: "secondViewController")
It means it will live until the first view controller is destroyed, and of course - will be reused.
Instead, you should create it as needed.
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
// Create the second view controller
let secondViewController = main.instantiateViewController(withIdentifier: "secondViewController")
let secondViewControllerProperties = secondViewController as! secondViewController
secondViewControllerProperties.receivedSelectedSectionValueFromFirstVc = indexPath.section
secondViewControllerProperties.receivedSelectedRowValueFromFirstVc = indexPath.row
// The below is the relevant content of a UILabel inside the tapped tableView cell by the user that get send to the secondViewController for it to be displayed as its NavigationBar title:
secondViewControllerProperties.selectedUniversalBeamSectionDesignation = arrayWithAllDataRelatedToUbsSections.filter({ $0.sectionSerialNumber == "\(arrayWithAllSectionsSerialNumbers[indexPath.section])" }).map({ $0.fullSectionDesignation })[indexPath.row]
self.present(secondViewControllerProperties, animated: true, completion: nil)
}
}
Remove the lazy var of course, it is no longer needed.
Also, you could just do:
let secondViewController = main.instantiateViewController(withIdentifier: "secondViewController") as! SecondViewController instead of casting it later, it's a bit cleaner.

Change destination viewController when editing is true or false

I have a viewControllerwith a tableViewwhich contains all clubs, the user added. The user can reorder the tableViewCellswith the moverowatfunction. If he selects a club, he comes to a tableViewwith all members from the club. Now I want to implement the ability, to get to another viewController where he can edit the content of the cell.
I have created this, but now it doesn't work:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableViewClub.isEditing == true{
self.navigationController?.pushViewController(EditClubViewController() as UIViewController, animated: true)}
if tableViewClub.isEditing == false{
self.navigationController?.pushViewController(MemberViewController() as UIViewController, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if !tableViewClub.isEditing {
guard let destination = segue.destination as? MemberViewController,
let selectedRow = self.tableViewClub.indexPathForSelectedRow?.row else {
return
}
destination.club = clubs[selectedRow]
}}
When tableView.isEditing, then a viewController with a black background is shown. When !tableView.isEditing, this error is shown:Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value. I think it is because I have no storyboard segues. But is it possible, to have two segues from the tableViewCell? Or how should I solve this problem?
Don't use Interface Builder's segue. Instantiate the destination view controller manually so you can control which one you are transitioning to:
Interface Builder
Select the EditClubViewController and give it a Storyboard ID. Do the same to MemberViewController.
In code
In the first view controller:
override func viewDidLoad() {
super.viewDidLoad()
// Turn this on so rows can be tapped during editing mode
tableView.allowsSelectionDuringEditing = true
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let destinationVC: UIViewController
switch tableView.isEditing {
case true:
// If your storyboard isn't named "Main.storyboard" then put the actual name here
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "editClubViewController") as! EditClubViewController
// do your setup....
destinationVC = vc
case false:
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "memberViewController") as! MemberViewController
// do your setup...
destinationVC = vc
}
self.navigationController?.pushViewController(destinationVC, animated: true)
}

Swift - How to use pushViewController in NSObject

I have a slide in/out side menu which is called when leftBarButtonItem in nab bar is tapped.
And I coded the slide menu with NSObject and I know NSObject doesn't have the pushViewController method.
navigationController?.pushViewController
I have a menu in UITableView in the NSObject and I want push viewController.
How can I make this work? Thank you.
import UIKit
class SlideMenuLauncher: NSObject, UITableViewDelegate,
UITableViewDataSource {
...
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let destinationVC: UIViewController
switch indexPath.row {
case 0:
destinationVC = ControllerA()
case 1:
destinationVC = ControllerB()
default:
destinationVC = HomeController()
}
self.navigationController?.pushViewController(destinationVC, animated: false)
}
...
1.
You can make a #property of your parentVC in SlideMenuLauncher class.
var parentVC: UIViewController?
and then you can use this instead of self.
parentVC!.navigationController?.pushViewController(destinationVC, animated: false)
2.
You can post a notification instead of pushing from SlideMenuLauncher class and pass the destinationVC as object in notification. Observe this notification in your parentVC then fetch the destinationVC from notification object and push the controller.
3.
You can make a block or delegate of didSelectRowAt event.
Block Example:
/// Declare a block in `SideMenuLauncher`
typealias TableEventBlock = (_ controller: UIViewController) -> Void
var tableEventBlock: TableEventBlock?
/// In table did select method
if tableEventBlock != nil {
tableEventBlock!(destinationVC)
}
You need to define its call back in parentVC (You can define it anywhere, Do it in viewDidLoad:) and will have to use SideMenuLAuncher's instance.
sideMenuLauncherInstance.tableEventBlock = { controller in
self.navigationController?.pushViewController(controller, animated: false)
}

pass data to previous view without segue,#IBaction swift

I have a View1 when i click on textbox i am going to view2(table view) to pick a value. I want to send the picked value to view1 for that textbox.
The controls are created programmatically so i am not using segue,IBActions.
I am trying to use the protocol methods still no success. Here is what i have tried.
class DynamicSuperView: UIViewController,UITableViewDelegate,UITableViewDataSource,dropdownDelegate,UITextFieldDelegate
{
func setValue(value:AnyObject)
{
print("dynamic view delegate method executed")
self.labelText = value as! String
//return selectedValue;
}
override func viewDidLoad() {
}
}
The second class is here with delegate method..
protocol dropdownDelegate {
func setValue(value: AnyObject);
}
class testClass: UIViewController,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate {
var delegate:dropdownDelegate! = nil
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vcName = names[indexPath.row]
print ("Table view cell clicked and value passed: \(vcName)")
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}
self.navigationController?.popViewController(animated: true)
delegate.setValue(value: "Testing delegate")
}
}
Once i select the value in the tableview i am calling the delegate method and trying to pass that value but no success.
I don't want to create the new instance of the previous view controller because i will lose the data already entered by the user, so i am popping the current view controller and going to the previous view controller.
Please suggest if my approach i correct or not?
ERROR:
fatal error: unexpectedly found nil while unwrapping an Optional value
Thank you in advance
Try this:
view func ButtonPressed() {
print("Button Pressed!!") // This will create the new instance of the view controller.
let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "Storage") as! testClass
vc.delegate = self
self.navigationController?.pushViewController(vc, animated:true)
}
You are not setting the delegate to first view controller.