Protocol Crashes When Nil

I am trying to transfer my object data from my HockeyDetailVC tableView to my FavouritesVC tableView using a protocol called addThis (Conformed FavouritesVC to the protocol), the data will be sent by clicking on a button but my issue is I get the message the delegate is nil and my program crashes.

HockeyDetailVC

protocol addThis {
    func addFav(data: CurrentPlayers)
}

    var item: CurrentPlayers?   //what I want to transfer to FavouritesVC
    
    var delegate: addThis?

        func sendData() {
        if delegate != nil {
            let data = item!
            delegate?.addFav(data: data)
            print("This is the data being transferred: \(data)")
        } else {
            print("The delegate is nil")
        }
    }
    
    @IBAction func addToFav(_ sender: Any) {
        sendData()
        print("Favourite button Pressed")     //button is pressed but data not sent
    }

FavouritesVC

  var currentFav: CurrentPlayers?

  var favArr = [CurrentPlayers]()

   func addFav(data: CurrentPlayers) {
        currentFav = data
    }
    
       override func viewDidLoad() {
        super.viewDidLoad()
        favArr.append(currentFav!) //crashes here delegate is nil

    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if segue.identifier == "r" {
          print("segue identifier", segue.identifier)
          let hockeyDetailVC: HockeyDetailVC = segue.destination as! HockeyDetailVC
          hockeyDetailVC.delegate = self
          print("destination HockeyDetailVC is", hockeyDetailVC)
      }
    } 

Class CurrentPlayers

class CurrentPlayers {
    var photoUrl: String
    var position: String
    var team: String
    var yahooName: String
    var birthCity: String
    var birthState: String
    var status: String
    var catches: String
    var shoots: String
    var jerseyNumber: Int
    var largePhoto: String
    
    init(photoUrl: String, position: String, team: String, yahooName: String, birthCity: String, status: String, catches: String, shoots: String, birthState: String, jerseyNumber: Int, largePhoto: String) {
        
        self.yahooName = yahooName
        self.photoUrl = photoUrl
        self.position = position
        self.team = team
        self.birthCity = birthCity
        self.status = status
        self.catches = catches
        self.shoots = shoots
        self.birthState = birthState
        self.jerseyNumber = jerseyNumber
        self.largePhoto = largePhoto
        
    }

FavouritesVC seems to be nil initially, so you'd need to handle that. At least, I don't see where you first set the value.

PS

This seems to be about UIKit's life cycle, you might want to ask over Apple Developer Forums instead

The issue I have is because something in the HockeyDetailVC is making what I want to transfer nil.

Terms of Service

Privacy Policy

Cookie Policy