Search code examples
iosxcodeprotocolsswift5mac-catalyst

class object passed in delegate method becomes <uninitialized> in Mac catalyst


object passed in delegate method becomes uninitialized in class where protocol is implemented. but same object have valid address in class from where delegate was called. This happens only in maccatalyst same code works perfectly in iOS and iPadOS

Protocol Declaration

 protocol ASPatientSearchDelegate: class {
    func moveToPaitentProfileScreen(patient: ASCardEntity)
}

Delegate variable declaration

    weak var delegate: ASPatientSearchDelegate? = nil

Delegate calling

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let patient = self.searchResults[indexPath.row]

                self.delegate?.moveToPaitentProfileScreen(patient: patient)
}

Method Implementation

extension ASAppointmentViewController: ASPatientSearchDelegate {
        func moveToPaitentProfileScreen(patient: ASCardEntity) {
    
            guard let json = patient.details as? JSON else { return }
    }
}

Delegate Assigned in ASAppointmentViewController

   @IBAction func searchButtonAction(_ sender: UIButton) {

        let searchViewController = ASPatientSearchViewController(nibName: ASPatientSearchViewController.className, bundle: nil)

        searchViewController.popoverPresentationController?.delegate = self
        searchViewController.modelController.delegate = self
}

Class Used

class ASCardEntity: NSObject {
    var details: Any?
}

Solution

  • It was instance scope issue. I have declared ASPatientSearchViewController instance variable to class scope

    Instance variable declaration

    class ASAppointmentViewController: ASBaseViewController {
        var searchViewController: ASPatientSearchViewController?
    }
    

    I changed below code

    @IBAction func searchButtonAction(_ sender: UIButton) {
    
            let searchViewController = ASPatientSearchViewController(nibName: ASPatientSearchViewController.className, bundle: nil)
    
            searchViewController.popoverPresentationController?.delegate = self
            searchViewController.modelController.delegate = self
    }
    

    To

    if self.searchViewController == nil {
            self.searchViewController = ASPatientSearchViewController(nibName: ASPatientSearchViewController.className, bundle: nil)
            
        }
        self.searchViewController.popoverPresentationController?.delegate = self
        self.searchViewController.modelController.delegate = self