Swift: Delegate is nil

gmoraleda

I'm trying to create an AppCoordinator which holds the different ViewControllers in my app:

class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    window = UIWindow(frame: UIScreen.main.bounds)

    let appCoordinator = AppCoordinator()
    window?.rootViewController = appCoordinator.initialTabBarController()
    window?.makeKeyAndVisible()
    return true
}
// ...


import SnapKit

class AppCoordinator {

    private let initialTabController = TabBarController()
    private let cars = CarProvider.sharedInstance.getCars()

    init() {
        var viewControllers = [ViewController]()
        viewControllers.append(carListViewController())

        initialTabController.setViewControllers(viewControllers, animated: true)
    }

    private func carListViewController() -> CarListViewController {
        let controller = CarListViewController(cars: cars)
        print(self)
        controller.delegate = self
        return controller
    }
}

// MARK: - CarListViewControlerDelegate
extension AppCoordinator: CarListViewControlerDelegate {
    func didPullToRefresh() {
        print("Did pull")
    }
}

My CarListViewController looks like this:

import UIKit

protocol CarListViewControlerDelegate: class {
    func didPullToRefresh()
}

class CarListViewController: ViewController {

    weak var delegate: CarListViewControlerDelegate?

    // MARK: Interface Properties
    private let tableView = TableView()
    private let refreshControl = UIRefreshControl()

    private var cars: [Car]?

    // MARK: Initializers
    init(cars: [Car]) {
        super.init(nibName: nil, bundle: nil)
        self.cars = cars
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - Actions
extension CarListViewController {

    @objc private func refresh() {
        delegate?.didPullToRefresh()
        refreshControl.endRefreshing()
    }
}

My refresh method gets called when I pull to refresh in my UITableView, but the protocol method didPullToRefresh doesn't. When I check on the delegate, it's value is nil.

Sh_Khan

You need a strong reference so make it an instance var inside AppDelegate

let appCoordinator = AppCoordinator()

OR

var appCoordinator:AppCoordinator! 

self.appCoordinator = AppCoordinator()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related