0

In my Swift 3/Obj-C application, I'm trying to set the delegate of my rootviewcontroller to its navigation controller but am getting the following error:

Cannot assign value of type 'NavController.Type' to type 'RootViewControllerDelegate'

NavController.swift

@available(iOS 10.0, *)
@objc class NavController: UINavigationController, RootViewControllerDelegate {

    static func instantiate() -> NavController? {
        let storyboard = UIStoryboard.init(name: "MyStoryboard", bundle: nil)
        let navVC = storyboard.instantiateViewController(withIdentifier: "NavController") as? NavController

        let rootVC = navVC?.viewControllers.first as! RootViewController
        rootVC.delegate = self // <<<< ERROR OCCURS HERE

        return navVC
    }

    func pressedNextButton()
    {
        NSLog("Next button works!")
    }
}

RootViewController.swift

@objc protocol RootViewControllerDelegate {
    func pressedNextButton()
}

@available(iOS 10.0, *)
@objc class RootViewController: UIViewController, NSFetchedResultsControllerDelegate, UITableViewDataSource, UITableViewDelegate {

    var delegate: RootViewControllerDelegate?

    @IBAction func nextButton(_ sender: UIBarButtonItem) {
        self.delegate?.pressedNextButton()
    }
}

MainProgram.m

@interface MYQAddDeviceViewController () 
     @property (nonatomic, strong) NavController * navVC;
@end

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navVC = [NavController instantiate];
}

Any ideas on how I can resolve that error?

Vee
  • 1,821
  • 3
  • 36
  • 60
  • Why did you put @objc before the class definition?Both are subclasses of UIViewController. – Mozahler Mar 03 '17 at 03:23
  • Those swift classes are used in the Obj-C portion of my app which requires the use of @objc. – Vee Mar 03 '17 at 03:47
  • You get that for free by subclassing off of uiviewcontroller. In other words you no longer need it. – Mozahler Mar 03 '17 at 04:42
  • So you're correct about the NavController class but not about RootViewController. RootViewController needs the @objc bc the app uses RootViewControllerDelegate protocol which requires the prefix. But, this exchange is not relevant to the question. Thanks for the tip though. – Vee Mar 03 '17 at 15:24
  • Sure. It's not really my wheelhouse, but I was hoping I could help. – Mozahler Mar 03 '17 at 17:51

1 Answers1

3

You're getting that error because the line

rootVC.delegate = self

is inside a static func and in that context, self refers to an instance of the NavController metaclass, i.e. NavController.Type instead of NavController.

You want:

if let navVC = storyboard.instantiateViewController(withIdentifier: "NavController") as? NavController,
    let rootVC = navVC.viewControllers.first as? RootViewController {

    rootVC.delegate = navVC
}
Dave Weston
  • 6,527
  • 1
  • 29
  • 44