简体   繁体   English

视图控制器切换时变量意外重置为 0

[英]Variable unexpectedly resetting to 0 when View Controller Switched

I had a variable called "results" in a ViewController called DetailViewController which is given a value, and is printed correctly in FirstViewController:我在名为 DetailViewController 的 ViewController 中有一个名为“results”的变量,它被赋予一个值,并在 FirstViewController 中正确打印:

extension FirstViewController: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostTableViewCell
        
        cell.typeLabel.text = "Name: \(posts[indexPath.row].typeOfFood)"
        cell.titleLabel.text = "Title: \(posts[indexPath.row].title)"
        cell.locationLabel.text = "Location: \(posts[indexPath.row].location)"
        cell.nameLabel.text = "Name: \(posts[indexPath.row].name)"
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        print("Select Row \(indexPath.row)")
        var result = indexPath.row
        tableView.deselectRow(at: indexPath, animated: true)
//        self.performSegue(withIdentifier: "showDetail", sender: nil)
        let mainStoryBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
        guard let detailViewController = mainStoryBoard.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController else{
            print("couldnt find vc")
            return
        }
        let detailVC = DetailViewController()
        detailVC.result = indexPath.row
        print(detailVC.result)
        self.present(detailViewController, animated: true, completion: nil)



    }
}

But then when my app switches to another ViewController called DetailViewController, The variable result is always printed and stored as 0. DetailViewController:但是当我的应用程序切换到另一个名为 DetailViewController 的 ViewController 时,变量结果始终打印并存储为 0。DetailViewController:

import UIKit
import Firebase
import FirebaseDatabase
class DetailViewController: UIViewController {

    @IBOutlet weak var backButton: UIBarButtonItem!
    @IBOutlet weak var nameOfUserLabel: UILabel!
    @IBOutlet weak var typeOfFoodNeededLabel: UILabel!
    @IBOutlet weak var amountOfFoodNeededLabel: UILabel!
    @IBOutlet weak var reasonNeededLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var locationLabel: UILabel!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var messageButton: UIButton!
     var posts = [Posts]()
    var rowNumber = String()
    var result = Int()
    override func viewDidLoad() {
        super.viewDidLoad()
        var rowNumber = Int()
        loadPosts()
print(result)
//        nameOfUserLabel.text = posts[result].name

    }
    
    func loadPosts() {
        Database.database().reference().child("Posts").observe(.childAdded){(snapshot: DataSnapshot) in
            if let dict = snapshot.value as? [String: Any]{
                
                let titleText = dict["Title"] as! String
                let typeofFoodText = dict["Type of Food"] as! String
                let descriptionText = dict["Description"] as! String
                let amountNeededText = dict["Number of Items Needed"] as! String
                let locationText = dict["Location"] as! String
                let nameText = dict["Name of User"] as! String
                let reasonNeeded = dict["Reason for Donation"] as! String
                
                
                let post = Posts(titleText: titleText, typeOfFoodText: typeofFoodText, descriptionText: descriptionText, amountNeededText: amountNeededText, locationText: locationText, nameText: nameText, reasonNeededText: reasonNeeded)
                 
                self.posts.append(post)
                print(self.posts)

                self.nameOfUserLabel.text = self.posts[self.result].name
                self.descriptionLabel.text = self.posts[self.result].description
                self.typeOfFoodNeededLabel.text = self.posts[self.result].typeOfFood
                self.amountOfFoodNeededLabel.text = self.posts[self.result].amountNeeded
                self.reasonNeededLabel.text = self.posts[self.result].reasonNeeded
                self.locationLabel.text = self.posts[self.result].location

                
                
            }

        }


    }
    ```

How can I fix this?我怎样才能解决这个问题? I mainly want the value it is given in FirstViewController to carry over to the DetailViewController, but it keeps resetting back to 0.我主要希望它在 FirstViewController 中给定的值延续到 DetailViewController,但它不断重置回 0。

You are passing the result variable to the new instance detailVC (detailVC.result) while the right instance for the passed variable is detailViewController (detailViewController.result).您将结果变量传递给新实例detailVC (detailVC.result),而传递变量的正确实例是detailViewController (detailViewController.result)。

Please replace the following in your shared source code:请在您的共享源代码中替换以下内容:

This这个

let mainStoryBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
guard let detailViewController = mainStoryBoard.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController else{
                print("couldnt find vc")
                return
            }
let detailVC = DetailViewController()
detailVC.result = indexPath.row
print(detailVC.result)
self.present(detailViewController, animated: true, completion: nil)

With

let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
    guard let detailViewController = mainStoryBoard.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController else{
                    print("couldnt find vc")
                    return
                }
    detailViewController.result = indexPath.row
    print(detailViewController.result)
    self.present(detailViewController, animated: true, completion: nil)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 访问另一个视图控制器的功能时意外发现nil - unexpectedly found nil when accessing another view controller's functions Swift:如何使后台功能即使在切换到其他视图控制器时也能保持运行 - Swift: how to make a background function that keeps running even when I switched to a different view controller 将View Controller用作辅助视图的委托时,展开可选项时失败,意外发现nil - Using View Controller as the delegate for an auxilliary view fails with unexpectedly found nil when unwrapping an optional 当尝试从表视图转到视图控制器时,我收到此错误:Unexpectedly found nil while unwrapping - When trying to segue to a view controller from a table view i get this error: Unexpectedly found nil while unwrapping 标签栏中的视图控制器(调用另一个vc作为弹出窗口),在切换标签时从标签栏层次结构中删除 - View controller (that calls another vc as a popup) in a tab bar, gets removed from tab bar hierarchy when tabs are switched 按下搜索栏时切换到另一个视图 controller 时意外发现 nil - unexpectedly found nil when switching to another view controller when search bar is pressed 将UITabBarController设置为根视图控制器时,如何修复应用程序委托中的“意外找到nil” - How to fix “Unexpectedly found nil” in app Delegate when setting UITabBarController as root view controller 点击视图的一部分会意外地将视图更改为以前的视图控制器 - tapping on portion of view changes view to previous view controller unexpectedly 滚动时重置表视图单元格信息 - Table view cell information resetting when scrolling 导航回该视图时,Swift动画未重置 - Swift animation not resetting when navigating back to that view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM