new to stackoverflow so please let me know if extra context needs to be provided but I have an xcode project (fitness app) and in it I have a tab bar controller , two view controllers called ProfileViewController and CalorieViewController that has no segue relationship, but are part of the same tab bar. I want to pass total calories from the calorieVC to profileVC to do some calculations (totalCalories/dailyValue) and i have opted to use delegate pattern which I followed according to some videos and textbook but in my console I it says my delegate is nil.
So far I have define the Delegate Protocol:
protocol CalorieViewDelegate: AnyObject {
func didUpdateTotalCalories(_ getTotalCalories: Double)
}
Step 2: Create a Delegate Property:
var delegate: CalorieViewDelegate?
var totalCalories: Double = 0.0 {
didSet {
delegate?.didUpdateTotalCalories(getTotalCalories: totalCalories)
}
}
Step 3: Implement the Delegate Method ():
func updateTotalCalories() {
let totalCalories = breakfastFoods.reduce(0, { $0 + $1.calories }) +
lunchFoods.reduce(0, { $0 + $1.calories }) +
dinnerFoods.reduce(0, { $0 + $1.calories }) +
snackFoods.reduce(0, { $0 + $1.calories })
delegate?.didUpdateTotalCalories(getTotalCalories : totalCalories)
totalCaloriesLabel.text = "\(totalCalories)"
print(totalCalories)
if let delegate = delegate {
delegate.didUpdateTotalCalories(getTotalCalories: totalCalories)
print("Delegate called with totalCalories: \(totalCalories)")
} else {
print("Delegate is nil, cannot call didUpdateTotalCalories")
}
}
Step 4: Set the Delegate (ProfileViewController):
var calories: Double = 0.0
var dailyValue: Double = 2000.0
extension ProfileViewController: CalorieViewDelegate {
func didUpdateTotalCalories(getTotalCalories: Double) {
calories = getTotalCalories
print(calories)
}
}
Here is some more relevant code from ProfileVC:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let calorieVC = CalorieViewController()
calorieVC.delegate = self
}
My project builds but I need to pass that data over to finish the last calculations in the profileVC and I can't find a reason why it won't do that.

You can also Resolve the Problem by using notification Observer instead of Delegate Methods Like, when you update the total calories you can post the Notification Observer there using the code. You can also pass the Data using Userinfo like :
and where you want to act like in some other class you can add the following code in ViewDidLoad() Method :
and add the following Objective method in the same class
you can Modify the code According to your needs.