我正在努力解决ViewControllers之间的状态问题。
导航路径如下;
1。用户从VenueDetailsVC
导航到DiscoverVC
,并像这样传递Venue
对象:
func presentDiscoverVC(){
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
discoverVC.venue = self.venue!
discoverVC.showBackButton = true
DispatchQueue.main.async {
self.presentDetail(discoverVC)
}
}
2。然后,用户可以从DiscoverVC
导航到PreferencesVC
并传递相同的Venue
对象,同时清除本地Venue
对象,如下所示:
class DiscoverVC: UIViewController{
var venue: Venue?{
didSet{
print("DiscoverVC venue name: \(venue?.name ?? "venue name")")
}
}
@IBAction func preferencesBtnTapped(_ sender: Any) {
guard let preferencesVC = storyboard?.instantiateViewController(withIdentifier: "PreferencesVC") as? PreferencesVC else { return }
preferencesVC.selectedVenue = self.venue!
presentDetail(preferencesVC)
}
override func viewWillAppear(_ animated: Bool) {
print("inside viewWillAppear venue: \(venue?.name ?? "venue name")")
}
override func viewWillDisappear(_ animated: Bool) {
venue = nil
}
}
3。然后,用户从DiscoverVC
导航回到PreferencesVC
,并传递相同的Venue
对象
@IBAction func doneBtnTapped(_ sender: Any) {
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
discoverVC.venue = self.selectedVenue!
DataService.run.updateUserDiscoveryPreferences(forUID: Auth.auth().currentUser!.uid, discoverableBool: discoverable!, preferences: preferences) { (success) in
self.dismissDetail()
}
}
问题:Venue
内的DiscoverVC
对象是否为零,即使它已在上述第三步中从PreferencesVC
传递回来了? < / p>
这是控制台输出:
答案 0 :(得分:0)
执行此操作时:
@IBAction func doneBtnTapped(_ sender: Any) {
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
discoverVC.venue = self.selectedVenue!
您没有设置提供首选项VC的Discover VC的venue
。您正在设置全新 Discover VC的venue
。
您可以使用委托模式将venue
传递回去。
创建一个PreferencesVCDelegate
:
protocol PreferencesVCDelegate: class {
func preferencesVC(_ vc: PreferencesVC, didDismissWithVenue venue: Venue)
}
在delegate
中添加一个PreferencesVC
属性:
weak var delegate: PreferencesVCDelegate?
用对委托方法的调用替换设置venue
的行:
@IBAction func doneBtnTapped(_ sender: Any) {
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
delegate?.preferencesVC(self, didDismissWithVenue: self.venue)
出示PreferencesVC
时,将self
设置为代表:
@IBAction func preferencesBtnTapped(_ sender: Any) {
guard let preferencesVC = storyboard?.instantiateViewController(withIdentifier: "PreferencesVC") as? PreferencesVC else { return }
preferencesVC.selectedVenue = self.venue!
preferencesVC.delegate = self
presentDetail(preferencesVC)
}
并使DiscoverVC
符合PreferencesVCDelegate
。在此处设置发现VC的venue
extension DiscoverVC: PreferencesVCDelegate {
func preferencesVC(_ vc: PreferencesVC, didDismissWithVenue venue: Venue) {
self.venue = venue
}
}