In order to obtain values from a previous viewController, I use a didSet
on a structure.
class ReviewViewController: UIViewController, UITextFieldDelegate {
var detailBuilding: Building? {
didSet {
configureView()
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
CKContainer.default()
}
override func viewWillAppear(_ animated: Bool) {
print("this override ran")
navigationItem.hidesBackButton = false
}
func configureView() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "RatingAttributes")
print("the buildingID is \(String(describing: detailBuilding?.buildingID))")
request.predicate = NSPredicate(format: "buildingID == %@", String(describing: detailBuilding?.buildingID))
print("configuration ran")
do {
let result = try context.fetch(request)
//assert(result.count < 2)
//print("the result we got was \(result[0])")
for data in result as! [NSManagedObject] {
print("The data was \(data.value(forKey: "buildingID")) ")
}
} catch {
print("Failed to retreive core data")
}
}
}
However, using print statements in the func configureView()
, I am able to tell that the function runs 3 times. However, if I remove the call to configureView()
from viewWillAppear()
, then the view will not appear; if I remove it from didSet
, then the values of detailBuilding (e.g detailBuilding.rating
) will be nil. Though the third time the function runs, the values of detailBuilding are always nil anyway, meaning I can't use them.
In the previous viewController I have:
@objc func addReviewAction(_ sender: UIButton) {
print("ran this correctly")
//navigationController?.setNavigationBarHidden(true, animated: true)
let controller = ReviewViewController()
controller.detailBuilding = detailBuilding
controller.navigationItem.title = ""
navigationItem.hidesBackButton = true
let backItem = UIBarButtonItem()
backItem.title = ""
backItem.tintColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
navigationController?.navigationItem.backBarButtonItem = backItem
navigationController?.pushViewController(ReviewViewController(), animated: true)
}
I have checked multiple times to make sure I am not accidentally calling configureView() from anywhere else.
My questions are: Why is configureView()
running multiple times? Why is detailBuilding
nil on the 3 rd out of 3 times. And should I be using a different method for acquiring detailBuilding, as I need the values it contains for my NSPredicate.
Thank you.